Here is my code:
#include <iostream>
#include <memory>
#include <vector>
class var {
private:
double value_;
std::shared_ptr<var> left_;
std::shared_ptr<var> right_;
public:
var(const double& v) : value_(v){};
friend var operator+(const var& l, const var& r) {
var result(l.value_ + r.value_);
left_ = std::make_shared<var>(l.value_);
right_ = std::make_shared<var>(r.value_);
return result;
}
friend std::ostream& operator<<(std::ostream& os, const var& var) {
os << var.value_;
return os;
}
};
int main() { var a(1); }
The error I am getting is as follows:
test.cpp: In function ‘var operator+(const var&, const var&)’:
test.cpp:17:9: error: invalid use of non-static data member ‘var::r_’
17 | r_.push_back(std::make_shared<var>(l.value_));
| ^~
test.cpp:10:39: note: declared here
10 | std::vector<std::shared_ptr<var>> r_;
| ^~
I am struggling to understand why I am getting the error in the title.
Is there a workaround?
left_ = ...
andright_ = ...
should beresult.left_ = ...
andresult.right_ = ...
. You just forgot to name the instance whose members you want to assign. The error message should be pretty clear.left_
andright_
are members, and they aren't static so you need to access them via an instance.r_
or any invocation ofpush_back
in the code you have posted. Therefore any attempt at answering your question is speculation.operator+=
as a member, which modifies the object that it's applied to. Then implementoperator+
by creating a result object with a copy of one of the values, and adding the other value to it with+=
. Voila: nofriend
declarations!operator+
does, it doesn't seem that+=
makes sense. I provided generic advice for arithmetic types; this isn't one.