2012-11-15 178 views
0

下面是我的简化代码,它需要您关于实施不良多态性的宝贵意见。抽象基类扩展

class X 
{ 
    public: 
     void test(); 
    protected: 
     virtual void foo() const = 0; 
}; 


class Y : public X 
{ 
    public: 
     void foo(){ cout << "hello" << endl; } 
}; 


int main() 
{ 
    X *obj = new Y(); 
} 

我在编译时出现以下错误。

test.cpp: In function ‘int main()’: 
test.cpp:23: error: cannot allocate an object of abstract type ‘Y’ 
test.cpp:14: note: because the following virtual functions are pure within ‘Y’: 
test.cpp:9: note: virtual void X::foo() const 

回答

4

应该是

class Y : public X 
{ 
    public: 
     void foo() const { cout << "hello" << endl; } 
}; 

因为

​​

void foo() 

是不一样的功能。

1

foo类Y不是常量,这样你就不会超载虚拟类X.

2

foo功能可按类Y具有与X不同的签名:: foo的

class Y : public X 
{ 
    public: 
    void foo() const { cout << "hello" << endl; } 
};