简体   繁体   中英

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(); 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.

Write...

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

to do this initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM