如何在C Plus Plus中更改分配的类值

时间:2019-06-16 15:26:56

标签: c++

我的应用程序中有home类,我想创建新的实例,例如:

#include <iostream>
#include <string>

using namespace std;

class home{
public: 
    string address = "default path";
};


int main()
{
    home person1;
    person1.address = "path 1";

    // doing some filter and sorting 

    home person2 = person1;
    person2.address = "path after assignment";

     cout << person2.address <<  endl;
     cout << person1.address <<  endl;
}

在这种情况下,我想更改第二个人的地址:

// output : 
// person 2: path after assignment
// person 1: path 1

但是它对person1.address无效,它是path 1

如何通过此输出引用person1来分配person2

// output : 
// person 2: path after assignment
// person 1: path after assignment

1 个答案:

答案 0 :(得分:1)

如果您希望person2是对person 1的引用,请替换:

home person2 = person1;

使用

home& person2 = person1;