c++ - 指向类对象的指针 vector

标签 c++ class object pointers stdvector

我在理解指向类对象的指针 vector 时遇到问题,我尝试了一个测试代码来尝试理解它,但是每当我输入一个名称并尝试输出它时,它会打印出数字而不是我输入的实际名称进入。我希望有人能向我解释这一点,因为我对这些概念还很陌生。

还有 Pets[0]->print(); 始终打印:

cout << "in main: " << Pets[0] << endl; 

打印。

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;
}

最佳答案

Pet 的构造函数没有分配参数,因此它仍然是空的。

写...

Pet::Pet(const string& Name) : name(Name) { }

做这个初始化。

关于c++ - 指向类对象的指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56500467/

相关文章:

java - 将字符串/整数转换为对象数组

c# - 自定义异常 C#

c++ - 在 openGL 中注册回调时出现编译错误

c++ - 在 C++ 中通过引用和值传递

c++ - 将 .ui 文件链接到 C++

php - 在 CodeIgniter 中找不到错误类 Controller

c++ - qt编译成功但运行失败

java - 加载jar库 加载库

python - python中获取类对象的生命周期

java - 同步与同步的区别