开发者

Cannot assign pointer in a self-referential object in Visual Studio 2010

开发者 https://www.devze.com 2023-01-19 01:09 出处:网络
I am learning C++ and i currently have some questions that i don\'t know the answe开发者_如何学运维rs. I create this header file Object1.h and can compile this file but when i run the Test.cpp, Visual

I am learning C++ and i currently have some questions that i don't know the answe开发者_如何学运维rs. I create this header file Object1.h and can compile this file but when i run the Test.cpp, Visual Studio throw an error because of access violation by *sibling. The strange thing is I can run it using Dev C+ and it return only value 2.Therefore I want to ask why assigning *sibling will create an error and why i can't change Person B's address using setAddress(). I will really appreciate if any one can give me some answer or hints. Thanks in advance.


//This is Object1.h
#include <iostream>
using namespace std;

class Person{
public:
    Person(int ID);
    void setAddress(string addr);
    string getAddress();
    void addSibling(Person *p);
    Person getSibling();
    int ID;
private:    
    string address;
    Person *sibling;
};

Person::Person(int ID){
    this->ID = ID;
}

void Person::setAddress(string addr){
    this->address = addr;
}

string Person::getAddress(){
    return address;
}

void Person::addSibling(Person *p){
    *sibling = *p;
}

Person Person::getSibling(){
    return *sibling;
}

//This is Test.cpp
#include <iostream>
#include <string>
#include "Object1.h"
using namespace std;

int main(){
    Person A(1);
    Person B(2);
    A.addSibling(&B);
    // Change the address of person B through person A's getSibling()
    A.getSibling().setAddress("123 Street");

    cout << B.getAddress() <<endl;
    cout << B.ID;

    system("Pause");
    return 0;
}


Using operator * assumes that you deal with some data resided by address stored in this variable. Let's review your code:

*sibling = *p;

You trying to copy by value. This is wrong because sibling points to nowhere. It is even not a NULL, it is unpredictable. The correct line will be:

sibling = p;

So you tell that would store pointer to another instance.


One notable problem is that you're returning by value in getSibling(), so you'll get a copy of the sibling rather than that actual sibling. Any changes you make will be to the temporary object.

As others have noted, you're addSibling function should be sibling = p. That's the source of your error.

But be sure to correct your getSibling function otherwise your setAddress won't do what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消