在C中返回当前对象(* this)?
发布时间:2020-12-16 10:29:17 所属栏目:百科 来源:网络整理
导读:我有以下代码: 代码1 class Student { int no; char grade[M+1]; public: Student() { no = 0; grade[0] = ' '; } void set(int n,const char* g) { no = n; strcpy(grade,g); } const Student getObject() { return *this; } void display() const { cout
我有以下代码:
代码1 class Student { int no; char grade[M+1]; public: Student() { no = 0; grade[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(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |