【发布时间】:2019-09-16 17:59:54
【问题描述】:
如果我有测试代码:
Number const * n = nullptr;
double val = 0;
std::cin >> val;
n = new Integer( int( val ));
if( n->intValue() != int( val )) {
std::cout << "intValue() is wrong\n";
}
而且我有一个 Integer 类,为了能够评估 n->intValue(),是否意味着我必须在 Integer 类中创建一个方法调用 intValue()?
我试图创建一个方法,但它显示错误“const class Number”没有名为“intValue”的成员。
我的班级代码:
#include <iostream>
using namespace std;
// Base class Number
class Number{
public:
Number(double theVal){
val = theVal;
cout << "Created a number with value " << val << endl;
}
protected:
double val;
};
class Integer : public Number{
public :
Integer(int val):Number(val){\
cout << "Created an integer with value " << val << endl;
}
int intValue(){
return (int)val;
}
double doubleValue(){
return (double)val;
}
};
class Double : public Number{
public :
Double(double val):Number(val){
cout << "Created a double with value " << val << endl;}
int intValue(){
return (int)val;
}
double doubleValue(){
return (double)val;
}
};
【问题讨论】:
-
如果
n是Number*则编译器无法确定它确实指向Integer对象 -
也许
Number这个基类应该是一个抽象的多态基类,函数作为抽象的virtual函数? -
@drescherjm 抱歉,我刚刚添加了它
-
等等,我刚刚意识到 intValue 不应该是一个函数,它应该是父/子类中的一个变量。
标签: c++ inheritance constructor parent children