c++重载操作符、构造函数等
C++ overloading operators,constructors and more
我已经创建了我自己的四个方法来处理字符串作为数字:
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
相关文章:
- 复制构造函数,赋值操作符重载
- 通过调用Move赋值操作符实现Move构造函数
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- 当目标类有多个构造函数时,消除强制转换操作符的歧义
- c++复制构造函数,重载赋值操作符,方法get()
- c++操作符重载构造函数
- 类赋值操作符和复制构造函数
- 影响正确性的move构造函数/赋值操作符示例
- 如果没有定义Move语义(Move构造函数和Move赋值操作符),编译器是否默认优化
- 在c++构造函数中使用new操作符是否正确?
- c++中的操作符重载,无法调用双参数构造函数
- 即使类没有定义构造函数,也不能在类上调用c++默认的move赋值操作符
- 如果new操作符重载且构造函数为私有,则无法通过new创建对象
- c++:使用构造函数实现操作符
- 复制构造函数和赋值操作符都被调用
- 与智能指针相关的c++移动语义与复制构造函数和赋值操作符
- 为什么不是只有一个?复制构造函数和赋值操作符
- 这是构造函数操作符还是转换操作符?
- 可以通过在基类中声明复制构造函数/操作符private来使派生类不可复制吗?