字符串的赋值操作符

Assignment Operator for Char String

本文关键字:赋值操作符 字符串      更新时间:2023-10-16
#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"&")。这是更安全的(因为你不能意外地改变参数的内容)和更快,因为只需要复制一个(非常小的)引用,而不是参数的整个内容。