既存の C++ プロジェクトを拡張しています。2 つの親クラスから派生した基本クラスがあります。親の 1 つに純粋な仮想機能があります。その純粋仮想関数を、もう一方の親に実装された関数によって定義したいと考えています。
したがって、親の純粋仮想関数を定義する基本クラスの義務を別の親が満たしてほしいと思います。私は 2 つのアプローチを試しましたが、どちらもコンパイラ エラーにつながりました。
何か案は?
これは、私の最初のアイデアを示す C++ プログラムです。コンパイラがbase2
の の定義を使用することを期待していvfunc()
ます。
// 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()
これが私の2回目の試みです:
// 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