首页 > 解决方案 > (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 addToto改成Complex addTo要设置返回值,那怎么return a,哪个调用addTo呢?

标签: c++

解决方案


你的函数是void并且没有返回任何你不能的原因use a method of class continuously。您需要将返回类型从更改voidComplex &

Complex& addTo( Complex add )
  {
      this->real_ += add.real_;
      this->imag_ += add.imag_;
      return *this;
  }

你应该传递一个 ref 而不是 value。

您可以参考此链接以获取更多信息:https ://en.wikipedia.org/wiki/Fluent_interface


推荐阅读