【问题标题】:My friend functions are not getting access to private variables我的朋友函数无法访问私有变量
【发布时间】:2017-04-24 23:36:06
【问题描述】:

所以我正在尝试构建一个类,它可以保存有关原子元素的信息,然后用它们进行计算。我的重载 * 友元函数出现错误,它说变量 atom_weight 在函数的上下文中是私有的,但它是友元,所以它不应该是

// 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;
}

我的大多数操作员都遇到了类似的错误,但我的附加错误没有,即使我找不到任何区别。如果有人对如何解决这个问题有任何见解,那就太好了。

【问题讨论】:

  • 此函数与朋友声明不匹配。检查参数类型。
  • 你的“朋友”有点不对劲……

标签: c++ class operator-overloading friend


【解决方案1】:

同时是函数定义的函数声明与类中的函数声明不对应。像这样声明函数

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

【讨论】:

    猜你喜欢
    • 2021-08-16
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    相关资源
    最近更新 更多