Home > Back-end >  invalid use of non-static data member
invalid use of non-static data member

Time:12-28

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?

CodePudding user response:

Your friend var operator is not a member of the class.
In order to access data members it should specify the instance.

Therefore change:

  left_ = std::make_shared<var>(l.value_);
  right_ = std::make_shared<var>(r.value_);

To:

//vvvvvvv---------------------------------------
  result.left_ = std::make_shared<var>(l.value_);
  result.right_ = std::make_shared<var>(r.value_);

Note:
As commented above by @PeteBecker: in the general arithmetic case a more efficient approach would be to implement operator = as a member, and then implement operator in terms of it (create a copy of the 1st argument, use operator to add the 2nd to it and return it).
It is probably not relevant in this specific case, since operator = doesn't make much sense.

  •  Tags:  
  • c
  • Related