You are close. As mentioned in the comments, your addtwo()
function needs to return a reference to the class being added. You can do that by returning the dereferenced this
pointer for that instance. Since this
is a pointer to the current instance, to return a reference to type Complex
you will need to dereference this
removing the one level of pointer indirection making the return type Complex
, e.g.
Complex& addTwo(Complex add){
this->real_ += add.real_;
this->imag_ += add.imag_;
return *this;
}
While using a setter is fine to provide the initial values to the instance of your class, you really ought to write a constructor for the class to accomplish the same thing. You can add default value of 0
for each real_
and imag_
at that point, e.g.
public:
Complex (double real = 0, double imag = 0) : real_(real), imag_(imag) {}
Now you can initialize the Complex
instances at the time they are created, e.g. in main()
Complex a {1.1, 2.2},
b {1.1, 2.2},
c {1.1, 2.2};
Adding a friend function for std::ostream&
is a simple way to provide stream-based output operator for your Commplex
type, e.g.
friend std::ostream& operator << (std::ostream& os, const Complex& c) {
std::cout << "{" << c.real_ << "," << c.imag_ << "}\n";
return os;
}
Putting it altogether, you can write what you are attempting as follows, initializing each instance of Complex
through the constructor while having your set()
function available to change values for an instance, if needed.
#include <iostream>
class Complex{
private:
double real_;
double imag_;
public:
Complex (double real = 0, double imag = 0) : real_(real), imag_(imag) {}
void set(double m, double n){
this->real_ = m;
this->imag_ = n;
}
Complex& addTwo(Complex add){
this->real_ += add.real_;
this->imag_ += add.imag_;
return *this;
}
friend std::ostream& operator << (std::ostream& os, const Complex& c) {
std::cout << "{" << c.real_ << "," << c.imag_ << "}\n";
return os;
}
};
int main(){
Complex a {1.1, 2.2},
b {1.1, 2.2},
c {1.1, 2.2};
a.addTwo(a).addTwo(b).addTwo(c);
std::cout << a;
}
Example Use/Output
$ ./bin/complex_class
{4.4,8.8}
Look things over and let me know if you have further questions.