6

我有以下

class base
{
};

class derived : public base
{
  public:
   derived() {}
   void myFunc() { cout << "My derived function" << std::endl; }

};

我现在有

base* pbase = new derived();
  pbase->myFunc();

我收到错误 myFunc 不是 base 的成员函数。

如何避免这种情况?以及如何让 myFunc 被调用?

注意我应该让基类不包含任何功能,因为它是设计的一部分,上面的代码是大功能的一部分

4

4 回答 4

6

myfunc需要可从基类访问,因此您必须myfuncbase. 如果您打算base成为一个抽象基类,即无法实例化并充当接口的类,则可以将其设为纯虚拟:

class base
{
 public:
  virtual void myfunc() = 0; // pure virtual method
};

如果您希望能够实例化base对象,那么您必须提供一个实现myfunc

class base
{
 public:
  virtual void myfunc() {}; // virtual method with empty implementation 
};

There is no other clean way to do this if you want to access the function from a pointer to a base class. The safetest option is to use a dynamic_cast

base* pbase = new derived;

....
derived* pderived = dynamic_cast<derived*>(pbase);
if (derived) {
  // do something
} else {
  // error
}
于 2012-11-19T09:10:16.600 回答
6

If you are adamant that this function should NOT be a part of base, you have but 2 options to do it.

Either use a pointer to derived class

derived* pDerived = new derived();
pDerived->myFunc();

Or (uglier & vehemently discouraged) static_cast the pointer up to derived class type and then call the function
NOTE: To be used with caution. Only use when you are SURE of the type of the pointer you are casting, i.e. you are sure that pbase is a derived or a type derived from derived. In this particular case its ok, but im guessing this is only an example of the actual code.

base* pbase = new derived();
static_cast<derived*>(pbase)->myFunc();
于 2012-11-19T09:15:23.490 回答
3

To use the base class pointer, you must change the base class definition to be:

class base
{
public:
    virtual void myFunc() { }
};

I see no other way around it. Sorry.

于 2012-11-19T09:10:45.157 回答
1

You could add it as a member of base and make it a virtual or pure virtual function. If using this route however, you should also add a virtual destructor in the base class to allow successful destruction of inherited objects.

class base
{
public:
   virtual ~base(){};
   virtual void myFunc() = 0;
};

class derived : public base
{
  public:
   derived() {}
   void myFunc() { cout << "My derived function" << std::endl; }

};
于 2012-11-19T09:11:05.760 回答