代码之家  ›  专栏  ›  技术社区  ›  ESipalis

C++重载运算符、构造函数等

  •  1
  • ESipalis  · 技术社区  · 9 年前

    我创建了自己的四种方法来将字符串处理为数字:

    std::string addStrings(std::string,std::string);
    std::string subtractStrings(std::string,std::string);
    std::string multiplyStrings(std::string,std::string);
    std::string divideStrings(std::string,std::string);
    

    然后我决定创建大数的类(称为bin)。我对复制构造函数和复制赋值运算符有点陌生,所以我需要你的帮助来修复我的代码:

    class bin{
        private:
            std::string value;
        public:
            bin(){}
            bin(const char* v1){
                value = v1;
            }
            bin(std::string v1){
                value = v1;
            }
            bin(const bin& other){
                value = other.value;
            }
            bin& operator=(const bin& other){
                value = other.value;
                return *this;
            }
            bin& operator=(const char* v1){
                value = v1;
                return *this;
            }
            std::string getValue() const{
                return value;
            }
            friend std::ostream& operator<<(std::ostream&,bin&);
    };
    
    std::ostream& operator<<(std::ostream& out,bin& v){
        out << v.value;
        return out;
    }
    bin operator+(bin& value1,bin& value2){
        return bin(addStrings(value1.getValue(),value2.getValue()));
    }
    bin operator-(bin& value1,bin& value2){
        return bin(subtractStrings(value1.getValue(),value2.getValue()));
    }
    bin operator*(bin& value1,bin& value2){
        return bin(multiplyStrings(value1.getValue(),value2.getValue()));
    }
    bin operator/(bin& value1,bin& value2){
        return bin(divideStrings(value1.getValue(),value2.getValue()));
    }
    

    为什么这样做有效:

    bin d = a/c;
    std::cout << d << std::endl;
    

    但这并不是:

    标准::cout<&书信电报;a/c;

    (a和c较早宣布)。此外,运算符链接也不起作用,例如:

    bin d = a * b + d;
    

    投掷:

    no match for operator* (operands are bin and bin).
    

    非常感谢。

    2 回复  |  直到 9 年前
        1
  •  3
  •   Telokis    9 年前

    在这些操作员内部:

    operator<<
    operator+
    operator-
    operator*
    operator/
    

    你应该带 const bin& 而不是 bin& 。否则,您的函数将无法将临时参数作为参数。

    而且,当您链接运算符时,每个独立运算符返回的值都是临时的。

        2
  •  0
  •   NathanOliver    9 年前

    第一次,因为你的班级只有 std::string 成员,您不需要实现复制构造函数或赋值运算符,因为默认编译器提供的构造函数和赋值运算符对您来说非常适用。

    其次,所有操作员都应该将这些参数作为 const & 从而它们可以捕获临时对象。这也允许您将操作员链接在一起,如 foo + bar + cat