gpt4 book ai didi

c++ - 在 C++ 中返回当前对象 (*this)?

转载 作者:太空狗 更新时间:2023-10-29 19:44:38 24 4
gpt4 key购买 nike

我有以下代码:

代码 1

class Student {
int no;
char grade[M+1];
public:
Student() {
no = 0;
grade[0] = '\0';
}
void set(int n, const char* g) {
no = n;
strcpy(grade, g);

}
const Student getObject() {
return *this;
}
void display() const {
cout << no << ", " << grade << endl;
}
};

代码 2:

// no change from code 1
const Student& getObject() {
return *this;
}
// no change from code 1

正如我正在阅读的书所解释的那样,代码 1 和代码 2 的 getObject() 的区别在于代码 2 的 getObject() 返回对当前对象的引用,而不是拷贝(出于效率原因)。

但是,我测试了(代码2)如下:

测试代码:

Student harry, harry1;
harry.set(123, "ABCD");

harry1 = harry.getObject();
harry1.set(1111,"MMMMMM");
harry.display(); // Line 1 => displayed: 123, ABCD
harry1.display(); / Line 2 => displayed: 1111, MMMMMM

我不明白。如果 getObject() 返回一个引用,那么测试代码中的第 1 行也应该显示 111,MMMMMM?因为我认为 harry1 应该包含 harry 对象的地址???还是我误解了什么?

最佳答案

尽管 harry.getObject() 是对原始对象的引用,但您随后通过赋值破坏了它:

harry1 = harry.getObject();

执行复制。

相反:

Student const& harry1 = harry.getObject();

关于c++ - 在 C++ 中返回当前对象 (*this)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com