Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;类错误';常量类编号';没有名为'的成员;intValue';_C++_Inheritance_Constructor_Parent_Children - Fatal编程技术网

C++ C++;类错误';常量类编号';没有名为'的成员;intValue';

C++ C++;类错误';常量类编号';没有名为'的成员;intValue';,c++,inheritance,constructor,parent,children,C++,Inheritance,Constructor,Parent,Children,如果我有测试代码: 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"; } Number const*n=nullptr; 双val=0; 标准:cin>>va

如果我有测试代码:

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";
}
Number const*n=nullptr;
双val=0;
标准:cin>>val;
n=新整数(int(val));
如果(n->intValue()!=int(val)){
std::cout intValue(),这是否意味着我必须在Integer类中创建一个方法调用intValue()

我试图创建一个methode,但它显示错误“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;
        }
};
#包括
使用名称空间std;
//基类数
班号{
公众:
数字(双倍于VAL){
val=theVal;

cout我猜n的类型是Number*,因此编译器事先无法知道它是否是子类之一。您可以添加

virtual int intValue() = 0;

如果
n
是一个
Number*
,那么编译器无法确定它是否真的指向一个
Integer
对象可能基
Number
类应该是一个抽象的多态基类,函数是抽象的
virtual
函数?@drescherjm抱歉,我刚刚添加了它等等,我刚刚意识到intValue不应该是一个函数,它应该是父/子类中的一个变量。可以这样做,但这个函数对来说没有意义,但必须包含在
类Double
类complex
中。推荐阅读:谢谢,以前没有读过,读得很好但是rocknoos在Double类中也有函数
int intValue()
,所以这里可以使用纯虚空。但是,是的,我也不会这么做。