将成员函数的返回类型引用到C++中的自定义类
Reference return type of member functions to custom classes in C++
我有以下代码:
#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;
}
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何正确实现和访问运算符的各种自定义枚举器
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 自定义先决条件对移动分配运算符有效吗
- 使用VS Code和CMake Tools运行自定义命令
- 如何创建从Maya(或类似程序)到虚幻引擎的自定义数据导出插件
- std::ranges::elements_view,用于自定义类似元组的数据
- 跟随整数索引列表的自定义类迭代器
- 参数化自定义CMake工具链
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 如何在自定义类中启用'auto loops'?
- 使用QJsEngine在Qt中注册自定义类型
- Qt自定义QPush按钮未显示在布局上
- 自定义对象的dlib序列化在gcc中失败
- 自定义创建QFuture
- 如何在QT中的自定义视频小工具t上绘制矩形