我只需要知道如何讓大小、索引和計數器在另一個函式中被呼叫時保持它們的值。現在它們只是在被呼叫時被賦予隨機值,而不是我在建構式中初始化它們的值。我怎樣才能解決這個問題?此代碼的目標是制作一個程式,該程式從程式的用戶(通過鍵盤)捕獲一串單詞并將輸入的單詞添加到字串的動態陣列中。這是 array.cpp 檔案
#include "array.h"
using namespace std;
Array::Array()
{
int size = 100;
int index = 0;
int counter = 0;
counter ;
index ;
string *ptr = new string[size];
}
Array::~Array()
{
delete ptr;
ptr = nullptr;
}
void Array::populate()
{
string word;
cout << "Enter word to add to array: ";
cin >> word;
ptr[index] = word;
}
void Array::printContent()
{
cout << "Number of words in array: " << counter << endl;
cout << "Array size: " << size << endl;
cout << "Words in array: " << endl;
for (int i = 0; i < counter; i )
{
cout << ptr[i] << endl;
}
}
void Array::displayMenu() const
{
cout << "[1] Add Word\n"
<< "[2] Print Array Information\n"
<< "[3] Quit Program\n"
<< "Enter Choice: ";
}
int Array::getChoice(int & choice1)
{
cin >> choice1;
while (choice1 < 1 || choice1 > 3) {
cout << endl;
cout << "Invalid Entry!!" << endl;
cout << "Enter Choice: ";
cin >> choice1;
}
return choice1;
}
int Array::endProgram(int & start2)
{
start2 = 0;
cout << "\n\n\t\tThank you for using this system!!\n\n";
return start2;
}
這是 array.h 檔案
#include <iostream>
#include <string>
using namespace std;
class Array {
public:
Array();
~Array();
void populate();
void printContent();
void displayMenu() const;
int getChoice(int & choice1);
int endProgram(int & start2);
private:
int size;
int index;
int counter;
string *ptr;
};
最后這是 main.cpp 檔案
#include <iostream>
#include "array.h"
using namespace std;
int main() {
int choice = 0;
int start = 1;
Array theArray;
while(choice != 3)
{
theArray.displayMenu();
theArray.getChoice(choice);
if(choice == 1)
{
theArray.populate();
}
if(choice == 2)
{
theArray.printContent();
}
if (choice == 3)
{
theArray.endProgram(start);
}
}
}
uj5u.com熱心網友回復:
您在Array建構式中定義了新的區域變數并隱藏了同名的成員變數——這就是為什么不保留該值的原因。
您只需要在定義新變數時指定型別,而不是在分配給現有變數時。要分配給成員變數,這應該是:
Array::Array()
{
size = 100;
index = 0;
counter = 0;
ptr = new string[size];
...
}
此外,在建構式中使用建構式初始化器串列來初始化值更正確:
Array::Array()
: size{100},
index{0},
counter{0},
ptr{new string[size]}
{
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/434688.html
上一篇:已發布事件未訂閱或未發布
下一篇:否則沒有ifvba
