[英]Writing to an array class will not cout
代碼運行,但我無法讓cout
工作。 請幫助我,我是一個初學者,並且真的很難將我的數組內容獲取到 output。
cout << myArray[0].getSquareName();
是從不cout
的行。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class cSquare {
public:
string SquareName;
string getSquareName() const;
void setSquareName(string);
friend std::istream & operator >> (std::istream & is, cSquare & s);
};
// set method
void cSquare::setSquareName(string squareName)
{
squareName = SquareName;
}
//square name get method
string cSquare::getSquareName() const
{
return SquareName;
}
ostream & operator << (ostream & os, const cSquare & s)
{
os << s.getSquareName() << ' ';
return os;
}
istream & operator >> (istream & is, cSquare & s)
{
is >> s.SquareName;
return is;
}
int main()
{
string discard;
int i = 0;
const int MAX_SIZE = 26;
ifstream monopoly("monopoly.txt", ios::in);
if (monopoly.is_open())
{
cSquare myArray[MAX_SIZE];
getline(monopoly, discard);
string sname; //string to store what I read in from my file
while (i < MAX_SIZE && monopoly >> sname)
{
myArray[i].setSquareName(sname);//stores the string read in into the array
cout << myArray[0].getSquareName(); //it never cout's this
i++;
}
}
}
您的setSquareName()
方法將對象的SquareName
成員分配給輸入參數,這是錯誤的。 你需要做相反的事情,例如:
void cSquare::setSquareName(string sname)
{
//sname = SquareName;
SquareName = sname;
}
另外,這一行:
cout << myArray[0].getSquareName();
應該是這樣的:
cout << myArray[i];
通過這 2 個更改,代碼可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.