c++ - (c++) 如何在主函数中连续使用类的方法?
问题描述
#include <iostream>
using namespace std;
class Complex{
private:
double real_;
double imag_;
public:
void set(double m, double n){
this->real_ = m;
this->imag_ = n;
}
void addTo(Complex add){
this->real_ += add.real_;
this->imag_ += add.imag_;
}
};
int main(){
Complex a, b, c;
a.set(1.1, 2.2);
b.set(1.1, 2.2);
c.set(1.1, 2.2);
a.addTo(a).addTo(b).addTo(c); // problem.
return 0;
}
我必须使用那个表达式(a.addTo(a).addTo(b).addTo(c);
)。
如何在主函数中连续使用类的方法?
编译的时候说类的类型要在前面.addTo(b)
,如果我从void addTo
to改成Complex addTo
要设置返回值,那怎么return a
,哪个调用addTo
呢?
解决方案
你的函数是void
并且没有返回任何你不能的原因use a method of class continuously
。您需要将返回类型从更改void
为Complex &
Complex& addTo( Complex add )
{
this->real_ += add.real_;
this->imag_ += add.imag_;
return *this;
}
你应该传递一个 ref 而不是 value。
您可以参考此链接以获取更多信息:https ://en.wikipedia.org/wiki/Fluent_interface
推荐阅读
- c - 根据 PID 杀死一个进程
- tsql - 指定的文件组“客户”无效
- gnuplot - Gnuplot - 多个“xtic”参数
- php - 似乎没有调用 usort 比较函数
- vba - 将相同的宏应用于所有工作表
- c# - System.ObjectDisposedException:此解析操作已结束
- javascript - 复制没有重复的数据 - Google Apps 脚本
- mysql - SQL:有条件的 SUM
- azure - 创建 Web App Bot 时无法创建新的 Azure 存储
- javascript - 如何在表单提交时通过 jQuery 阻止 Cyrillic unicode