Search code examples
c++classoperator-overloadingfriend

My friend functions are not getting access to private variables


So I am trying to build a class that can hold information about atomic elements and then do calculations with them. I am getting an error with my overloaded * friend function that says the variable atom_weight is private within the context of the function, but it's a friend so it shouldn't be

// The chemical class
class Chemical{
        public:
        Chemical();
        Chemical(string chemsym);
        Chemical(string chemsym, int number, double weight);
        void get_element(string chemsym, ifstream& fin);
        void clear();
        friend Chemical operator +(Chemical& molecule, Chemical& element);
        friend Chemical operator *(const Chemical element, int multiplier);
        friend Chemical operator >>(istream& ins, Chemical element);
        friend Chemical operator <<(ostream& outs, Chemical element);
        string get_sym();
        int get_num();
        double get_weight();
        private:
        string chemsym;
        int atom_num;
        double atom_weight;
};

And then here is my function definition for my overloaded * operator.

Chemical operator *(const Chemical& element, int multiplier){
        Chemical tempele;
        string number;
        tempele.atom_weight = element.atom_weight * multiplier;
        number = itostr(mulitplier);
        tempele.chemsym = element.chemsym + number;
        return tempele;
}

Most of my operators are getting similar errors, but my addition one is not even though I can't find any difference. If anyone has any insight on how to solve this problem that would be great.


Solution

  • The function declaration that is at the same time is the function definition does not correspond to the function declaration in the class. Declare the function like

    friend Chemical operator *(const Chemical &element, int multiplier);
                                              ^^