C++ C++;重载运算符、构造函数等
我创建了自己的四种方法来将字符串作为数字处理:C++ C++;重载运算符、构造函数等,c++,constructor,copy-constructor,chaining,operand,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); 然后我决定创建big numbe
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);
然后我决定创建big number的类(称为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()));
}
抛出:
no match for operator* (operands are bin and bin).
谢谢大家! 在这些操作员内部:
operator<<
operator+
operator-
operator*
operator/
operator首先,由于您的类只有std::string
成员,因此您不需要实现复制构造函数或赋值运算符,因为默认编译器提供的运算符对您来说可以正常工作
其次,所有操作符都应该将这些参数作为常量&
,以便它们可以捕获临时对象。这还允许您将运算符链接在一起,如foo+bar+cat
bin(
在运算符中是多余的;返回值是从return
之后的表达式构造的。因此,您可以编写return addStrings(
等)。
no match for operator* (operands are bin and bin).
operator<<
operator+
operator-
operator*
operator/