通过引用设置类时会发生什么情况
What happens when a class is set by reference
我正在从使用 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;
}
相关文章:
- 将指针分配给另一个指针时会发生什么情况?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 在什么情况下,我想在 C/C++ 代码中使用内联汇编代码
- 发生注入类名时会发生什么情况?(C++)
- 在什么情况下,需要共享智能指针而无法使用唯一指针?
- 重新分配向量时,向量中的内存会发生什么情况
- 如果结构中的字符串比使用的 p/调用签名长或短,会发生什么情况?
- 为什么或在什么情况下,你会将参数作为C++中的引用(或指针)传递给函数?
- 如果我向一个12字节的缓冲区写入的字节数少于12,会发生什么情况
- 删除对象(具有不同类型)的引用时会发生什么情况?
- 如果我在 c++ 中以 new 的放置形式使用没有足够的内存,会发生什么情况?
- 使用 Google 基准测试时返回值会发生什么情况?
- 正在连接的等待条件变量的线程会发生什么情况?
- 如果未定义的C++行为符合 C 定义的行为,会发生什么情况?
- 在 C++ 中取消引用字符串时会发生什么情况
- 通过引用设置类时会发生什么情况
- 如果参数传递两次,会发生什么情况?一次按值,一次按引用?是否会修改
- 未分配返回未定义对象类型引用的 C++ 函数的返回值时会发生什么情况
- 当按引用传递参数存储在被调用方对象中,然后被调用方删除时会发生什么情况
- 取消引用不返回的函数时会发生什么情况?