c++ - 重载运算符函数失败

标签 c++ operator-overloading

这里我写了2个重载运算符:

stringb operator+(const stringb &a,const stringb &b)
{
    stringb temp;
    temp.len = a.len + b.len;
    temp.p=new char[(temp.len)+1];
    strcpy(temp.p, a.p);
    strcat(temp.p, b.p);
    return (temp);
}
stringb operator-(const stringb &a,const stringb &b)
{
    stringb temp;
    temp.len=a.len-b.len;
    temp.p=new char[temp.len+1];
    strcpy(temp.p,a.p);
    return (temp);
}

但是,当我编译实际代码时,除了调用这些运算符的部分外,整个代码都有效,而且我得到了垃圾。我的功能有什么问题?

编辑:stringb 类的声明:

class stringb
{
    public:
        char *p;
int len;
public:
    stringb()
    {
    len=0;
    p=0;
    }
stringb(const char *s)
{
    len=strlen(s);
    p=new char[len+1];
    strcpy(p,s);

}
stringb(const stringb &s)
{
    len=s.len;//strlen(s);
    p=new char[len+1];
    strcpy(p,s.p);
}
~stringb()
{
    delete p;
}

friend int operator==(const stringb &a,const stringb &b);
friend stringb operator+(const stringb &a,const stringb &b);
friend stringb operator-(const stringb &a,const stringb &b);
friend void putstring(const stringb a);

};

最佳答案

你的问题在这里:

~stringb()
{
    delete p; // <<<<<
}

如果 temp 超出您的运算符定义的范围,这将被执行。

为了让您的代码正常工作,您需要正确实现 Rule of Three 在您的 stringb 类中。你也可以看看这个不错的 IDE one sample , P0W已根据您的代码进行设置。

关于c++ - 重载运算符函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20164565/

相关文章:

c# - 操作数的顺序对于 C# 中的重载 == 运算符是否重要

c++ - 运算符重载 = 修改原始对象

c++ - CUDA 设备仿函数工厂

c++ - 分配对临时对象的引用 C++ Visual

c++ - std::array<std::array<T, N2>, N> 数据成员上的括号运算符重载

Groovy - 如何在带有编译静态的 Map 中重载 '+=' 运算符?

c++ - C++ 中用户定义的字符串转换(类似于 Python 中的 __repr__)

c++ - MacPorts: “Error: clang-4.0 has been replaced by clang-8.0; please install that instead”,但我已经安装了clang-8.0

c++ - 在析构函数中将类成员设置为 null

c++ - 临时调用 operator<<