我的友元函数无法访问私有变量
My friend functions are not getting access to private variables
所以我正在尝试构建一个 class 可以保存有关原子元素的信息,然后用它们进行计算。我的重载 * friend 函数出现错误,指出变量 atom_weight 在函数的上下文中是私有的,但它是一个 friend 所以它不应该是
// 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;
};
然后这是我重载的 * 运算符的函数定义。
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;
}
我的大多数操作员都会遇到类似的错误,但我的另一个操作员却没有,尽管我找不到任何区别。如果有人对如何解决这个问题有任何见解,那就太好了。
同时为函数定义的函数声明与class中的函数声明不对应。像
这样声明函数
friend Chemical operator *(const Chemical &element, int multiplier);
^^
所以我正在尝试构建一个 class 可以保存有关原子元素的信息,然后用它们进行计算。我的重载 * friend 函数出现错误,指出变量 atom_weight 在函数的上下文中是私有的,但它是一个 friend 所以它不应该是
// 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;
};
然后这是我重载的 * 运算符的函数定义。
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;
}
我的大多数操作员都会遇到类似的错误,但我的另一个操作员却没有,尽管我找不到任何区别。如果有人对如何解决这个问题有任何见解,那就太好了。
同时为函数定义的函数声明与class中的函数声明不对应。像
这样声明函数friend Chemical operator *(const Chemical &element, int multiplier);
^^