2014-05-12 79 views
-4

我有一个类test_d公开继承类test_b。类test_d具有函数getValues(),我需要使用类test_b的对象调用。我尝试使用dynamic_castreinterpret_cast,但它没有奏效。有没有其他方法可以做到这一点?使用派生函数从基类

class test_b { 
// this is the base class 
}; 

class test_d : public test_b { 
// this is the derived class 

public int getValues() const; // this is the function I need to use. 
}; 

test_b* objB = new test_d; 
dynamic_cast<test_d*>(objB)->getValues(); // this is what I am doing. 
+1

这听起来像一个严重有瑕疵的设计... –

+1

你可以详细说明“它没有工作”? 'dynamic_cast'看起来应该起作用(忽略基类不应该知道其派生类型的事实)。 – juanchopanza

+0

看起来像是一些破解的OOP – alex

回答

2

在你的界面,你应该声明你的方法,纯虚函数,然后在派生类中,你应该写一个实现

class test_b 
{ 
public: 
    virtual int getValues() const = 0; 
}; 

class test_d : public test_b 
{ 
public: 
    virtual int getValues() const 
    { 
     return m_value; 
    } 
}; 

从你main()的地方:

test_b* objB = new test_d; 
objB->getValues(); 

这是OOP的基础知识:界面和界面的实现

相关问题