通过引用设置类时会发生什么情况

What happens when a class is set by reference

本文关键字:什么情况 引用 设置      更新时间:2023-10-16

我正在从使用 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;
}

一切都设置正确,我只是不明白如何。

作业正在进行中。 尝试添加:

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;.profile是一个变量,将为其分配一些值。在这种情况下,operator =将在此变量上执行,因此类用户可以修改类值的分配方式。你可以自由地(作为类编写者)做任何事情,在这个赋值运算符中你想做什么。您不必像在复制构造函数中那样执行相同的操作(尽管您应该这样做,因为用户会感到惊讶)。而且您甚至不必返回*this,尽管如果您不这样做,那么您的用户会感到惊讶。

编辑: 在 C++11 和将来还有移动构造函数/赋值:

class Profile{
public:
string name;
int age;
Profile();
~Profile();
Profile( const Profile &profile); 
Profile( Profile &&profile); 
Profile &operator = (const Profile &);
Profile &operator = (Profile &&);
};
Profile &Profile::operator = ( Profile &&profile){
cout << "COPY ASSIGNMENT" << endl;
age = age/3;
return *this;
}

当您从临时变量分配(或创建)时,这些将被"触发"。例如:

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

在第二行中,您将获得临时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已经初始化,不会再创建!当你使用赋值运算符时,编译器将调用,嗯,the assignment operator

如果未提供实现,编译器将为您生成一个,请记住,仅在需要时才应根据 3/5/0 规则实现这些方法。

最后,赋值运算符应如下所示:

Profile& operator=(const Profile &other) {
this->name = other.name;
this->age = other.age;
return *this;
}
相关文章: