假设我有一个基类A和派生类B和C。我希望能够通过A类型的引用指针来执行派生函数的方法。我尝试使用虚拟函数:
class A
{
public:
virtual std::string a() { return "a() of a"; }
virtual std::string b();
virtual std::string c();
};
class B : public A
{
public:
std::string a() { return "a() of b"; }
std::string b() { return "b() of b"; }
};
class C : public A
{
public:
std::string a() { return "a() of c"; }
std::string c() { return "c() of c"; }
};
int main(int argc, char** argv)
{
B b;
C c;
A* a1 = &b;
A* a2 = &c;
std::cout << a1->b() << std::endl;
std::cout << a2->c() << std::endl;
return 0;
}但我一直在想:
/tmp/ccsCMwc6.o:(.rodata._ZTV1C_ZTV1C+0x18):对
A::b()' /tmp/ccsCMwc6.o:(.rodata._ZTV1B[_ZTV1B]+0x20): undefined reference toA的未定义引用::C()‘/tmp/ccsCMwc6.o:(.rodata._ZTI1C_ZTI1C+0x10):对A’的typeinfo for A' /tmp/ccsCMwc6.o:(.rodata._ZTI1B[_ZTI1B]+0x10): undefined reference to类型信息的未定义引用
帮助?
发布于 2015-08-30 20:18:40
编译器将为每个类生成一个虚拟函数表(vtbl),该表指向该类所有虚拟函数的实现,对于A类,它希望找到A::b()和A::c()的实现。
如果您不想实现它们,则需要将它们声明为纯虚拟的:
class A
{
public:
virtual std::string a() { return "a() of a"; }
virtual std::string b() = 0;
virtual std::string c() = 0;
};发布于 2015-08-30 15:22:48
所有虚拟函数都需要有一个定义(实现)。
发布于 2015-08-30 15:40:49
在我看来没问题。如果只实例化继承的类,则不需要在基类中有定义。
它是什么编译器?
https://stackoverflow.com/questions/32298091
复制相似问题