c++ - 基类如何使用另一个父函数来满足父函数的纯虚函数的定义

标签 c++ gcc g++ vtable pure-virtual

我正在扩展现有的 C++ 项目。我有一个派生自两个父类的基类。 parent 之一具有纯虚函数。我希望该纯虚函数由另一个父项中实现的函数定义。

所以,我希望另一个父类满足基类定义父类的纯虚函数的义务。我尝试了两种方法,都导致了编译器错误。
有什么想法吗?

这是一个 C++ 程序,展示了我的第一个想法,希望编译器只使用 base2vfunc() 定义。

// This is my first approach, hoping the parent base2 of derived would satisfy the need to define
// base1's pure virtual vfunc.

class base1 {
public:
 virtual int vfunc() = 0;
};

class base2 {
public:
 int vfunc() { return 0;} //defined
};

class derived : public base1, public base2 {
public:
 //empty
};

int main()
{
 derived d;
 base1 & b1 = d;
 int result = b1.vfunc();
 return result;
}

编译器报告 derived 仍然是一个抽象类:

$ gcc a.cc 
a.cc: In function ‘int main()’:
a.cc:26: error: cannot declare variable ‘d’ to be of abstract type ‘derived’
a.cc:18: note:   because the following virtual functions are pure within ‘derived’:
a.cc:7: note:  virtual int base1::vfunc()

这是我的第二次尝试:

// This is my second attempt, defining a vfunc in the derived class that calls the other parent.

class base1 {
public:
 virtual int vfunc() = 0;
};

class base2 {
public:
 int vfunc() { return 0; } // defined
};

class derived : public base1, public base2 {
public:
 int vfunc() { return base2::vfunc(); } // call the other parent's vfunc
};

int main()
{
 derived d;
 base1 & b1 = d;
 int result = b1.vfunc();
 return result;
} 

我实际上希望它能帮我完成,但链接器却给我一堆我不明白的 vtable 错误:(Mac OS 10.6,gcc 4.2.1)

$ gcc inheritance_tester.cc 
Undefined symbols:
  "vtable for __cxxabiv1::__vmi_class_type_info", referenced from:
      typeinfo for derivedin ccmeHq8C.o
  "___cxa_pure_virtual", referenced from:
      vtable for base1in ccmeHq8C.o
  "___gxx_personality_v0", referenced from:
      _main in ccmeHq8C.o
      base2::vfunc()     in ccmeHq8C.o
      derived::vfunc()     in ccmeHq8C.o
      base1::base1() in ccmeHq8C.o
      base2::base2() in ccmeHq8C.o
      derived::derived()in ccmeHq8C.o
      CIE in ccmeHq8C.o
  "vtable for __cxxabiv1::__class_type_info", referenced from:
      typeinfo for base1in ccmeHq8C.o
      typeinfo for base2in ccmeHq8C.o
ld: symbol(s) not found

最佳答案

您需要从 base1 覆盖 vfunc。您可以按如下方式进行:

class derived : public base1, public base2 {
public:
 using base1::vfunc;
 int vfunc() { return base2::vfunc(); } // call the other parent's vfunc
};

关于c++ - 基类如何使用另一个父函数来满足父函数的纯虚函数的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3721375/

相关文章:

c++ - 用于 Linux 的 CreateTimerQueue

C++ 库链接问题

将 GNU C 编译为 C89

gcc - 使用较新的 gcc 调用 'lower_bound' 没有匹配函数

gcc - GCC/Clang 的 -framework 选项在 Linux 上工作吗?

linux - Visual Studio Express 2010 与 Linux gcc-4.3.2 上的 STL

找不到符号 "Embeddedrcall_Init"

c++ - 寻找更好的数据排序方法

c++ - 打印时前一个指针的值不同

c++ - 为什么当枚举或 int 值作为函数的 bool 参数传递时 gcc 不发出警告?