c++重载操作符、构造函数等

C++ overloading operators,constructors and more

本文关键字:构造函数 操作符 重载 c++      更新时间:2023-10-16

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

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 & lt; & lt;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&。否则你的函数将不能接受一个临时变量作为参数。

并且,当您链接操作符时,每个独立操作符返回的值都是临时的

首先,因为你的类只有一个std::string成员,你不需要实现复制构造函数或赋值操作符,因为默认编译器提供的这些将为你工作得很好。

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