将成员函数的返回类型引用到C++中的自定义类

Reference return type of member functions to custom classes in C++

本文关键字:C++ 自定义 引用 成员 函数 返回类型      更新时间:2023-10-16

我有以下代码:

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std ; 
class abc{
public :
string name;
abc & change_name(string s);
};
abc & abc::change_name(string s) {
this->name = s;
return *this;
};
int main(){
abc obj1 ;
abc temp ; 
temp = obj1.change_name("abhi");
cout<<"Name is : "<<obj1.name<<endl; \Prints - Name is : abhi
cout<<"Name is : "<<temp.name<<endl;  \Prints -Name is : abhi
\cout<<"Name is  "<<temp->name<<endl;  \\Error : base operand of '->' has non-pointer type 'abc'.
return 0;
}

abc的成员函数change_name(string s)返回类型为abc的指针。在 main 内部,我有一个abc类型的temp对象,它不是指针。我的问题是,当change_name(string s)的返回类型是指针但temp本身不是指针时,语句temp = obj1.change_name("abhi")如何工作?

此函数

abc & abc::change_name(string s) {
this->name = s;
return *this;
};

不返回指针。它返回对当前对象的引用。

所以在这个声明中

temp = obj1.change_name("abhi");

使用了默认的复制分配运算符。其实这句话相当于

temp = obj1;

您可以将对对象的引用视为其对象、对象、别名。

返回指针的函数可能如下所示

abc * abc::change_name(string s) {
this->name = s;
return this;
};

将您的原始程序与这个轻度更新的程序进行比较

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std ; 
class abc{
public :
string name;
abc * change_name(string s);
};
abc * abc::change_name(string s) {
this->name = s;
return this;
};
int main(){
abc obj1 ;
abc *temp ; 
temp = obj1.change_name("abhi");
cout<<"Name is  "<<temp->name<<endl; 
return 0;
}