C++ 使用基类的派生函数

C++ 使用基类的派生函数,c++,class,object,inheritance,C++,Class,Object,Inheritance,我有一个类test\u d,它公开继承类test\u b。类test\u d有一个函数getValues(),我需要使用类test\u b的对象调用该函数。我试着使用dynamic\u cast和reinterpret\u cast,但没有成功。还有别的办法吗 class test_b { // this is the base class }; class test_d : public test_b { // this is the derived class public int ge

我有一个类
test\u d
,它公开继承类
test\u b
。类
test\u d
有一个函数
getValues()
,我需要使用类
test\u b
的对象调用该函数。我试着使用
dynamic\u cast
reinterpret\u 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.
类测试{
//这是基类
};
类测试d:公共测试b{
//这是派生类
public int getValues()const;//这是我需要使用的函数。
};
测试b*objB=新测试d;
动态_cast(objB)->getValues();//这就是我正在做的。

在接口中,应该将方法声明为纯虚函数,然后在派生类中编写实现

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

class test_d : public test_b 
{
public:
    virtual int getValues() const
    {
        return m_value;
    }
};
从您的
main()
的某个地方:


这是OOP的基础:接口和接口的实现听起来像是一个有严重缺陷的设计……你能详细说明一下“它不起作用”吗?<代码>动态CaseStudio看起来应该已经工作了(忽略了基类不应该知道派生类型的事实)。为什么GETValk不是基类中的虚函数?<代码> public int GETValues()…< /C> >不是一个有效的C++代码,它是java。在
public
后面需要一个冒号,比如
public:
。发布一些(最小的)真实代码来重现问题。
test_b* objB = new test_d;
objB->getValues();