【问题标题】:Using Derived function from base class [closed]使用基类中的派生函数[关闭]
【发布时间】:2014-06-29 09:45:08
【问题描述】:

我有一个类test_d,它公开继承类test_btest_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.

【问题讨论】:

  • 这听起来像是一个严重缺陷的设计......
  • 您能否详细说明“它不起作用”? dynamic_cast 看起来应该可以工作(忽略基类不应该知道其派生类型的事实。)
  • 为什么getValues不是基类中的虚函数?
  • public int getValues() ... 不是有效的 C++ 代码,它是 Java。 public 之后需要一个冒号,例如 public:
  • 发布一些(最少的)真实代码来重现问题。

标签: c++ class object inheritance


【解决方案1】:

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

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 的基础:接口和接口的实现

【讨论】:

    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 2018-07-11
    相关资源
    最近更新 更多