[英]vector of pointers to class objects
I'm having a problem understanding vectors of pointers to class objects, I tried a test code to try and understand it but whenever I enter a name and try to output it, it prints out numbers instead of the actual name that I entered. 我在理解类对象指针的向量时遇到了问题,我尝试了一个测试代码来尝试理解它,但每当我输入一个名字并尝试输出它时,它会输出数字而不是我输入的实际名称。 I'm hoping someone can explain this to me as I'm new to these concepts. 我希望有人可以向我解释这个,因为我对这些概念不熟悉。
Also Pets[0]->print();
还有Pets[0]->print();
dosent print at all while: 剂量打印时:
cout << "in main: " << Pets[0] << endl;
prints. 打印。
class Pet
{
public:
string name;
Pet(const string&);
string getName() const
{
return name;
}
void setName(const string& Name)
{
name = Name;
}
void print()const;
}
int main()
{
vector<Pet*> Pets;
string names;
int done = NULL;
do
{
{
cout << "Name: ";
cin >> names;
Pets.push_back(new Pet(names));
cin.ignore();
}
cout << "Add another ?" << endl;
cin >> done;
} while (done != 0);
Pets[0]->print();
cout << "in main: " << Pets[0] << endl;
system("pause");
}
Pet::Pet(const string& Name)
{
}
void Pet::print()const
{
cout << "Name: " << name;
}
The constructor of Pet
does not assign the parameter, hence it remains empty. Pet
的构造函数不分配参数,因此它保持为空。
Write... 写...
Pet::Pet(const string& Name) : name(Name) { }
to do this initialization. 做这个初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.