【问题标题】:C++ class error'const class Number' has no member named 'intValue'C++ 类错误'const class Number'没有名为'intValue'的成员
【发布时间】: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;
        }
};

【问题讨论】:

  • 如果nNumber* 则编译器无法确定它确实指向Integer 对象
  • 也许Number这个基类应该是一个抽象的多态基类,函数作为抽象的virtual函数?
  • @drescherjm 抱歉,我刚刚添加了它
  • 等等,我刚刚意识到 intValue 不应该是一个函数,它应该是父/子类中的一个变量。

标签: c++ inheritance constructor parent children


【解决方案1】:

我猜 n 是 Number* 类型,所以编译器无法知道它是否是子类之一。你可以添加

virtual int intValue() = 0;

到你的父类。见纯虚函数here

【讨论】:

  • 可以做,但是这个函数对于class Double或者class complex来说是没有意义的。推荐阅读:stackoverflow.com/questions/56860/…
  • 谢谢,以前没读过,真的很好读。但是rocknoos 在Double 类中也有int intValue() 的功能,所以这里可以使用纯虚空。但是,是的,我也不会这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-23
  • 1970-01-01
相关资源
最近更新 更多