代码此外,重载不起作用

code in addition overload having no effect

本文关键字:重载 不起作用 代码      更新时间:2023-10-16

我目前正在翻阅一本C++的旧书,其中开发了一个"有理数"类来引入运算符重载等的想法。以下是本书中的一些示例代码:

接口

const Rational operator+(const Rational& Rhs) const;

实现:

const Rational Rational::operator+(const Rational& Rhs) const
{
    Rational Answer(*this);
    Answer += Rhs;
    return Answer;
}

复制构造函数执行您认为它会执行的操作,并且 += 运算符已正确重载。

我决定通过实现一个字符串类来练习一下,所以我采取了类似的方法。我的+=过载工作正常,但+似乎最终没有效果。

接口:

const String operator+(const String&) const;

实现:

const String String::operator+(const String& Rhs) const
{
    String Answer (*this);
    Answer += Rhs;
    return Answer;
}

其中复制构造函数(有效(定义为:

String::String(const String& str)
{
    unsigned _strlen = str.len() + 1;
    content = new char[_strlen];
    std::memcpy(content, str.content, _strlen);
    length = _strlen - 1;
    content[length] = '';
}

并且+=因以下原因而过载:

const String& String::operator+=(const String& Rhs)
{
    unsigned _Addl = Rhs.len();
    unsigned newLen = _Addl + length;  //length is member variable -- current length of content
    content = (char*) realloc( content, newLen+1 );
    std::memcpy(content+length, Rhs.content, _Addl);
    content[newLen] = '';
    return *this;
}

然而 - 虽然我可以得到正确的输出+=,但+运算符实际上无法返回一个串联的字符串。在函数内部使用调试输出时,Answer 保存正确的内容,但它返回原始字符串而不是串联字符串。我有一种感觉,这与const无处不在有关,但我尝试过没有它也没有好运气。

测试代码:

(主要(:

String s1 ("Hello");
String s2 (" World!");
String s3 = (s1+s2);       //prints "Hello" when s3 is output
cout << (s1+s2) << endl;   //prints "Hello"

常量字符* 的字符串构造函数

String::String(const char* str)
{
    unsigned _strlen = strlen(str) + 1;
    content = new char[_strlen];
    std::memcpy(content, str, _strlen);
    length = _strlen - 1;
    content[length] = '';
}

尽管您声称String::operator+=()已正确实现,但并未正确实现。

首先,如果失败,realloc()会返回NULL,并且您的代码不会对此进行检查。

其次,更关键的是,length成员没有更新。 由于您的代码调用 len() 成员函数来获取一个字符串的长度,并使用length成员来获取另一个字符串的长度,因此您的所有函数都需要确保这两个方法同步(即它们为给定的 String 实例提供一致的结果(。 由于length未更新,因此您的代码无法确保这一点。

可能也有比使用 C 样式内存分配更好的方法,但是(假设这是一个学习练习(我就不说了。

您没有为 Rational 类提供相关的代码,但如果它不起作用,您的代码可能会在各种构造函数和成员函数执行的操作之间表现出类似的不一致。