C++抽象基类调用自己的纯虚函数会导致"Undefined reference"
C++ abstract base class calling own pure virtual function results in "Undefined reference"
我有一个基类:
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;
};
以及一些派生类,例如:
class Bar : public Foo {
public:
Bar();
private:
const char* getClassName()
{
return "Bar";
}
};
上面的代码给出了"对Foo::getClassName()的未定义引用",我假设这是因为代码想调用Foo::getClassName((),但我如何让它像正常的虚拟调用一样调用函数?I.E.如何从Foo内部调用Bar::getClassName()?
编辑:忘记继承
fooList
中的项目必须使用new
、fooList[0] = new Bar()
创建。正如WeaselFox所说,Bar
必须继承自Foo
。
有两件事是未定义的:
Bar::Bar() is undefined
- Bar();
+ Bar() {}
并且fooList未定义:
+std::vector<Foo*> Foo::fooList;
以下是更正后的程序:
test.cpp:
#include <vector>
#include <iostream>
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;
};
std::vector<Foo*> Foo::fooList;
class Bar : public Foo {
public:
Bar() {};
private:
const char* getClassName()
{
return "Bar";
}
};
int main()
{
//intentionally leaked
Foo::fooList.push_back(new Bar());
Foo::fooList.push_back(new Bar());
Foo::fooList.push_back(new Bar());
Foo::printFoos();
}
输出:
Class: Bar
Class: Bar
Class: Bar
似乎bar
没有继承foo
。您需要声明继承:
class bar: public foo { ...
相关文章:
- OpenCV imwrite 函数导致'undefined symbol'
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 如何修复 cpp 中的"undefined reference to"错误,当调用刚性车身树中的函数时,如 doKinematics、CreateKinematicCache
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- 函数"Undefined symbol"错误
- 库路径绝对是正确的,可以创建所述库的实例,但在调用任何函数时"Undefined reference"
- C++'Undefined reference to'错误,尽管包含路径中的头文件中存在函数定义
- 如何在c 中留下一个声明的函数,例如haskell中的``undefined''
- CPU_ONLY构建:编译函数 Forward() 会给出错误"undefined reference..."
- 为什么我的复制构造函数出现"undefined reference to"错误?
- 我的一堆函数出现"undefined reference"错误,我不知道为什么
- "undefined reference to"不是模板构造函数,而是我尝试使用该模板的类的构造函数
- 使用自定义析构函数时出现"Undefined reference"错误
- "Undefined Symbols"但定义和声明了函数,没有错别字
- 从 C 文件调用C++函数会产生"undefined reference"编译器错误
- 构造函数/解构函数情况下的'undefined reference to vtable for'
- C++:除虚函数外," undefined reference to 'typeinfo for [class name]' "的原因是什么
- 在为 QScriptEngine 重新定义"print()"函数时返回"Undefined Value"有什么意义?
- GCC 为依赖于默认构造函数的模板化类中的静态数据成员提供"undefined reference"错误
- C++抽象基类调用自己的纯虚函数会导致"Undefined reference"