代码此外,重载不起作用
code in addition overload having no effect
我目前正在翻阅一本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
类提供相关的代码,但如果它不起作用,您的代码可能会在各种构造函数和成员函数执行的操作之间表现出类似的不一致。
相关文章:
- 重载运算符 (<<) cout 在 c ++ 中不起作用,当我互相减去两个矩阵时不起作用
- 为什么重载运算符>在参数声明 const 时不起作用?
- 重载"+="运算符:c+=a_times_b 有效,但 c+=a*b 不起作用?
- = 重载不起作用
- 类中的重载函数(Students())是输出输入的信息,但它不起作用
- 重载'='不起作用
- 二叉搜索树<<运算符重载不起作用
- 类构造函数重载不起作用
- c++中的函数重载不起作用
- 两个参数的运算符重载不起作用
- 流运算符重载不起作用
- 代码此外,重载不起作用
- 单例中的构造函数重载不起作用
- c++矩阵重载不起作用
- C++ostream重载不起作用
- 为什么模板运算符重载不起作用?
- 运算符 + 重载不起作用
- c++模板操作符重载不起作用
- sprintf_s模板库重载不起作用
- <<运算符重载不起作用;仍在打印对象地址