C++ 通过引用设置类时会发生什么

C++ 通过引用设置类时会发生什么,c++,C++,我将使用函数的结构值的C样式,通过PTRS到使用对象引用的C++风格。我不明白的是,当我通过引用传递一个对象,然后将其设置为一个新对象时,数据集是怎样的?我本以为它是复制构造函数,但它似乎没有任何效果 范例 #include <iostream> using namespace std; class Profile{ public: string name; int age; Profile(); ~Profile(); Profile( const

我将使用函数的结构值的C样式,通过PTRS到使用对象引用的C++风格。我不明白的是,当我通过引用传递一个对象,然后将其设置为一个新对象时,数据集是怎样的?我本以为它是复制构造函数,但它似乎没有任何效果

范例

#include <iostream>

using namespace std;

class Profile{
    public:
  string name;
  int age;
  Profile();
  ~Profile();
  Profile( const Profile &profile); 
};
Profile::Profile(){
    name = "BILLY BOB";
    age = 234;
}
Profile::~Profile(){}
Profile::Profile( const Profile &profile){
    cout << "COPY CONSTRUCTOR" << endl;
}

void GetProfile(Profile &profile){
    cout << &profile << endl;
    Profile p;
    // what's going on here?
    profile = p; 
}

int main()
{
    Profile p;
    p.name = "MIKE";
    p.age = 55;
    cout << p.name << endl;
    cout << p.age << endl;
    cout << &p << endl;
    GetProfile(p);
    cout << p.name << endl;
    cout << p.age << endl;
    return 0;
}
#包括
使用名称空间std;
班级简介{
公众:
字符串名;
智力年龄;
轮廓();
~Profile();
剖面图(施工剖面图和剖面图);
};
Profile::Profile(){
name=“比利•鲍勃”;
年龄=234岁;
}
配置文件::~Profile(){}
配置文件::配置文件(常量配置文件和配置文件){
作业正在进行中。
尝试添加:

class Profile{
    public:
  string name;
  int age;
  Profile();
  ~Profile();
  Profile( const Profile &profile); 
  Profile &operator = (const Profile &);
};
Profile &Profile::operator = ( const Profile &profile){
    cout << "COPY ASSIGNMENT" << endl;
    age = age/3;
    return *this;
}
当您将从临时变量分配(或创建)时,这些变量将被“激发”。例如:

Profile p;
p = Profile(...);

在第二行中,您将获得临时的
配置文件
值,移动赋值可能会以某种方式利用该值,因为该值无论如何都将被销毁。例如,字符串将传递其内容,而不是复制,等等。

我想首先声明复制构造函数不正确:变量不正确因此,在初始化时,它将无法按您认为的方式工作:

你应该像这样修复它:

Profile::Profile(const Profile &profile)
: name(profile.name) // copy name
, age(profile.age) // copy age
{
    cout << "COPY CONSTRUCTOR" << endl;
    age = age/3; // this variable was used without being initialized
}
Profile& operator=(const Profile &other) {
    this->name = other.name;
    this->age = other.age;
    return *this;
}

请注意,这是关于赋值与构造的关系,引用只是分散了对真实问题的注意力。@FrançoisAndrieux不确定GetProfile()中“分散对真实问题的注意力”是什么意思函数用于将引用参数的内容设置为新创建的配置文件对象。这将不包含在main()中设置的值函数。@peer_2_peer_2是的,但是如果你读了你写的东西,你会注意到问题的中心是引用。但是引用不会引起你的问题。@peer_2_peer_2我的意思是,我不知道如何详细说明。复制构造和复制赋值之间的区别只是不要求对象由可能是一个例子:哦,我看了,我只看了3的规则——我认为它是构造函数/析构函数/复制构造函数,但实际上是析构函数/复制构造函数/复制赋值是。在“更新”C++中,这个规则现在被命名为5的规则——你得到移动构造函数和移动赋值。“应该只在需要时实现”-这违反了3的规则,不是吗?@peer_2_peer_2 3的规则实际上是。它表示“如果一个类需要一个用户定义的析构函数、一个用户定义的复制构造函数或一个用户定义的复制赋值操作符,它几乎肯定需要所有三个。"。理想情况下,设计您的类,使编译器提供的构造函数、析构函数和赋值运算符工作良好。然后不要实现它们中的任何一个。这是规则的零部分。从问题的内容来看,OP似乎不理解规则的含义,但将其包含在答案中是有意义的。现在我请注意,他确实知道这个规则,所以我用一个链接更新了答案。谢谢你指出这一点。
Profile& operator=(const Profile &other) {
    this->name = other.name;
    this->age = other.age;
    return *this;
}