简体   繁体   中英

How can I access method in object when pointer of object is stored in vector?

In C++, with Visual Studio Code,

I made class Person. I made a vector <Person*> phonebook . I constructed an object Person newperson and pushed it in my vector phonebook And I want to access newperson.print() . So I wrote phonebook[i]->print but it shows a runtime error.

I thought it was a copy constructor problem, but after I added it, it was the same. And I also tried to separate by constructing a new dummy object, but it doesn't work either. How can I access to object's method through object's pointer stored in vector?

Person(const Person &oldperson)
        {
            firstname = oldperson.firstname;
            lastname = oldperson.lastname;
            phonenumber = oldperson.phonenumber;
        }
//This is my copy constructor,


void PrintAll()
{
    for(int i = 0; i < phonebook.size(); i++)
    {
        cout << "Hello " << i << endl;//it runs
        Person personprinter = Person(*phonebook[i]);
        cout << "Hello 2" << endl;//it does not run
        personprinter.Print();
    }
}
//This is my method where I will call object's method.

Expected: .Print() runs.

Actual: Person personprinter = Person(*phonebook[i]); doesn't run.

I think we need definition of phonebook and also to see the way you added object in it.

The object you added in phonebook have gone out of scope thus they have been deleted (you did not do a new to build the object).

Then you are using a pointer to a deleted object.

{
    Person newperson = Person(nameinarray[0], nameinarray[1], phonenumber);
    phonebook.push_back(&newperson);
}// closing the curly brace here calls delete on newperson  
// pointer in phonebook now points to a deleted object

VS

{
    Person* newperson = new Person(nameinarray[0], nameinarray[1], phonenumber);
    phonebook.push_back(newperson);
}  
// pointer in phone book is still valid 

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