字符串的赋值操作符
Assignment Operator for Char String
#include <iostream>
#include <string.h>
using namespace std;
class String
{
private:
enum { SZ=80 };
char str[SZ];
public:
String(){
strcpy(str, "");
}
String (const char s[]){
strcpy(str,s);
}
String operator = (String obj){
String newObj;
strcpy(newObj.str,obj.str);
return newObj;
}
void display(){
cout << str;
}
};
int main()
{
String s1("ABC");
String s3;
s3 = s1;
s3.display();
return 0;
}
我试图将一个字符串对象复制到第二个使用上述代码(赋值运算符)operator=
,为什么它不工作?我尽力了,但还是失败了。
您的赋值操作符不是赋值给String本身,而是赋值给一个临时变量,这将是正确的方法:
String& operator = (const String& obj) {
strcpy(str, obj.str); // in this line, obj is copied to THIS object
return *this; // and a reference to THIS object is returned
}
赋值操作符总是必须改变对象本身,并将值赋给对象。通常还返回对对象本身的引用。
你的代码中还有其他一些问题:
strcpy()不应该使用,因为它没有范围检查(缓冲区的大小),尽管是不安全的。
当使用字符串作为参数(或任何更大的对象,如类有很多成员,向量等),你应该使用const引用,就像我的例子("const"answers"&")。这是更安全的(因为你不能意外地改变参数的内容)和更快,因为只需要复制一个(非常小的)引用,而不是参数的整个内容。
相关文章:
- Qt PL/SQL - 赋值运算符 - 字符串缓冲区太小
- 将std::basic_string赋值给字符串
- c++中的重载赋值操作符
- c++类继承和赋值操作符
- 带引用类成员的赋值操作符
- 复制构造函数,赋值操作符重载
- c++派生类赋值操作符
- 通过调用Move赋值操作符实现Move构造函数
- 带有映射的赋值操作符
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- c++复制构造函数,重载赋值操作符,方法get()
- 用于具有const数据成员的类的move和右值赋值操作符
- 类赋值操作符和复制构造函数
- 赋值操作符重载
- 影响正确性的move构造函数/赋值操作符示例
- 当类是子类时重载赋值操作符
- 创建了自己的字符串类——重载赋值操作符和析构函数的错误
- 字符串类赋值操作符(+=)行为怪异
- 字符串的赋值操作符