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

标签 c++ constructor copy-constructor chaining operand

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

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;

这不是:

std::cout << a/c;

(a 和 c 之前声明过)。运算符链接也不起作用,例如:

bin d = a * b + d;

抛出:

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

谢谢!

最佳答案

在这些运营商内部:

operator<<
operator+
operator-
operator*
operator/

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

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

关于C++ 重载运算符、构造函数等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732556/

相关文章:

javascript - 为什么构造函数返回对象,而不是 JavaScript 中的原语?

c++ - 使用互斥锁 move 类的语义

c++ - 保证某个函数在销毁前被调用

c++ - CUDD C++ 接口(interface),用于将 bool 值转换为 BDD 和生成的最小项集(到割集)

c++ - 3D图形网格法 vector 旋转加倍

node.js - "this"构建后丢失? (ts/Node/express)

c++ - SecByteBlock 不接受字符串作为自定义键

Java - 如何只创建一个具有有效属性的对象?

c++ - 我们可以将参数传递给 C++ 中的复制构造函数吗

c++ - 为什么在此代码中使用复制构造函数?