我正试图从我的 2 级类(class)中找出这项作业。 我们将创建一个名为 Number 的类,派生自 std::string。 此类中唯一的代码是两个构造函数,一个默认构造函数和一个将字符串作为参数的构造函数。 我有:
class Number : public string {
public:
Number();
Number(string set);
}
然后构造函数被编码为:
Number::Number() : string("0") { } // default constructor sets data string to "0"
Number::Number(string set) : string(set) { }
到目前为止一切顺利。然后我们将采用我们一直在开发的两个类,Double 和 Integer,并将它们派生自 Number。在这两个类中,我们曾经分别使用 double 和 int 作为数据成员。现在,由于继承,我们应该有一个内置的数据部分(字符串)。我遇到的问题是,我所有的 operator=() 重载现在都是“在所有路径上递归”,导致运行时发生计算溢出。我将展示一个采用字符串的 Double 构造函数示例,以及导致无限递归的 equals 函数。
Double::Double(string d) : Number(d)
{
// overloaded constructor that takes a string argument
if (isNaN(d)) {
*this = "0.0";
}
else {
*this = d;
}
// used for setting the value of a data member with a string
void Double::operator=(string d)
{
if (isNaN(d)) {
*this = "0.0";
}
else {
*this = d;
}
}
}
我看到递归发生的地方,因为 *this 正在调用重载的 =,它会调用自身,因为我在 = 函数本身中使用 *this。那么将数据成员设置为提供的值的正确语法是什么。之前它只是 this->dataMemberName = provided value of proper type.
应该注意的是,我的非字符串构造函数确实设置了实例对象的值:
Double::Double(int d) : Number(to_string(d)){}
但是第二次我尝试对它们做任何事情,+ - */,= 函数被调用,然后错误再次发生。
最佳答案
只需添加:
using std::string::operator=;
缩写示例:
#include <string>
class Number : public std::string {
public:
};
class Double : public Number {
public:
using std::string::operator=;
Double()
{
*this="0.0";
}
};
关于c++ - 将派生自 std::string 的类派生的类的数据成员设置为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40295825/