C++ C++;抽象基类调用自己的纯虚函数会导致;“未定义引用”;
我有一个基本类:C++ C++;抽象基类调用自己的纯虚函数会导致;“未定义引用”;,c++,function,virtual,abstract-class,C++,Function,Virtual,Abstract Class,我有一个基本类: class Foo { public: virtual ~Foo() {} static void printFoos() { std::vector<Foo*>::iterator it; for(it=fooList.begin();it!=fooList.end();++it) { std::cout<<"
class Foo {
public:
virtual ~Foo() {}
static void printFoos()
{
std::vector<Foo*>::iterator it;
for(it=fooList.begin();it!=fooList.end();++it)
{
std::cout<<"Class: "<<(*it)->getClassName()<<"\n";
}
}
virtual const char* getClassName()=0;
static std::vector<Foo*> fooList;
};
上面的代码给出了“对Foo::getClassName()的未定义引用”,我假设这是因为代码想要调用Foo::getClassName(),但是我如何让它像通常的虚拟调用一样调用函数呢?例如,如何让它从Foo内部调用Bar::getClassName()
编辑:忘记了继承内容似乎
bar
没有继承foo
。您需要声明继承:
class bar: public foo { ...
必须使用
new
,dublist[0]=new Bar()创建dublist
中的项目。正如WeaselFox所说,Bar
必须继承自Foo
。有两件事是未定义的:
Bar::Bar() is undefined
- Bar();
+ Bar() {}
+std::vector<Foo*> Foo::fooList;
愚人是没有定义的:
Bar::Bar() is undefined
- Bar();
+ Bar() {}
+std::vector<Foo*> Foo::fooList;
呼叫代码在哪里?您可以粘贴它吗?至少在上面的代码中,Bar不是从Foo派生的。如果您在基类中将getClassName声明为public,那么它在派生类中不也应该是public吗?您的代码经过适当修改后,不会从g++-ansi-pedantic-Werror-Wall
中给出错误。你在用什么编译器?不可复制。那是个打字错误。对不起,我打了这个例子。@Brian-你应该一直复制/粘贴。
Class: Bar
Class: Bar
Class: Bar