繁体   English   中英

为什么我在 + 运算符重载函数返回的对象上重载 << 时会出错

[英]Why do I get an error when I overload the << on the object returned by the + operator overloaded function

class String
{
    char* array;
public:
    String(const char* s)
    {
        array = new char[strlen(s) + 1]{ '\0' };
        strcpy(array, s);
    }
    ~String()
    {
        if (array)
        {
            delete[]array;
        }
    }
    String operator+ (const char* p)   //返回对象
    {
        String temp(p);
        char* tempStr = temp.array;
        temp.array = new char[strlen(array) + strlen(tempStr) + 1]{ '\0' };
        strcpy(temp.array, array);
        strcat(temp.array, p);
        delete[]tempStr;
        return temp;
    }
    friend ostream& operator<<(ostream& output, String& x);   // <<函数重载只能定义成友元
};

ostream& operator << (ostream& output, String& x)  //对<<重载的方式
{
    output << x.array;
    return output;
}

int main()
{
    String string1("mystring");
    cout << string1 + "ab" << endl;
    cout << string1 << endl;
    return 0;
}

这是我第一次在这里问问题,所以如果有任何不好的描述,请原谅我:)

言归正传,我重载了+<<运算符,所以我想通过cout<<string1+"ab"<<endl得到输出“ mystringab ”,但是输出是乱码。

我认为+运算符重载函数可能有问题,有人可以告诉我问题出在哪里吗?

如果我想得到正确的结果,我应该如何重写重载的函数?

问题是重载operator<<的第二个参数不能绑定到String右值,因为第二个参数是对非 const String的左值引用

我应该如何重写重载函数?

您需要将重载的operator<<的第二个参数设为const String&以便它也可以与第二个参数"ab"一起使用,如下所示:

//---------------------------------------- vvvvv------------>low-level const added here
friend ostream& operator<<(ostream& output,const String& x);

同样在定义中做同样的事情:

//----------------------------------- vvvvv------------>low-level const added here
ostream& operator << (ostream& output,const String& x) 
{
    output << x.array;
    return output;
}

此外,请确保您的程序没有任何未定义的行为。 例如,通过确保仅在安全的情况下使用deletedelete[] (不再需要指针指向的数据)。 您可以使用 valgrind 等工具来检测一些基本问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM