2012-05-31 31 views
4

为什么此代码不能编译? (GCC 4.7.0)无法从派生指针访问公共基础成员

// Class with a simple getter/setter pair. 
class Base { 
public: 
    Base() : m_Value(0) { } 

    virtual ~Base() { } 

    // Getter 
    virtual int value() { return m_Value; } 

    // Setter 
    virtual void value (int Val) { m_Value = Val; } 

private: 
    int m_Value; 
}; 

// Derived class overrides the setter. 
class Derived : public Base { 
public: 
    void value (int Val) { 
      // do some stuff here... 
    } 
}; 

int main() 
{ 
    Derived * instance = new Derived(); 
    int x = instance->value(); // ERROR 
    return 0; 
} 

生成日志:从基地

test.cpp: In function 'int main()': 
test.cpp:29:25: error: no matching function for call to 'Derived::value()' 
test.cpp:29:25: note: candidate is: 
test.cpp:21:7: note: virtual void Derived::value(int) 
test.cpp:21:7: note: candidate expects 1 argument, 0 provided 

为什么编译器看不到 'int值()' 时使用派生*?

更改

Derived * instance = new Derived(); 

Base * instance = new Derived(); 

作品(但我需要在我的情况下得到的指针)。

也重命名基地getter/setter函数说getValue()和setValue(int)的作品。我可以为我的代码使用各种解决方法,但我只是很好奇为什么此代码无法编译。

+2

的可能重复[为什么在基类的派生类隐藏其他重载的重载函数?( http://stackoverflow.com/questions/1628768/why-does-an-overridden-function-in-the-derived-class-hide-other-overloads-of-the) – Mat

回答

11

这就是语言的工作方式:当一个子类覆盖名称的成员时,它隐藏了父类中所有未覆盖的名称。这是为了防止意外地组合应该作为集合覆盖的基本方法和父方法。

您可以将using Base::value;放入您的子类中以引入父级方法。

+0

谢谢,很好地解决了这个问题。 – QuasarDonkey

3

函数value派生类隐藏函数在基类中。

您需要携带的基类功能到派生类的为范围:

class Derived : public Base { 
public: 

    using Base::value; //<---- note this 

    void value (int Val) { 
      // do some stuff here... 
    } 
}; 
相关问题