从基类构造函数调用纯虚函数 [英] call to pure virtual function from base class constructor
本文介绍了从基类构造函数调用纯虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void PrintStartMessage()= 0
我想让每个派生类在它们的构造函数中调用
code> MyBase )构造函数
class MyBase
{
public:
virtual void PrintStartMessage()= 0;
MyBase()
{
PrintStartMessage();
}
};
class Derived:public MyBase
{
public:
void PrintStartMessage(){
}
};
void main()
{
派生的派生;
}
但我得到了一个链接器错误。
这是错误信息:
1> ------ Build started:项目:s1,配置:Debug Win32 --- ---
1>编译...
1> s1.cpp
1>链接...
1> s1.obj:错误LNK2019:未解析的外部符号public :$ void $ __thiscall MyBase :: MyBase(void)(?? 0MyBase @@ QAE @ XZ)
(@AUEXXZ)引用的函数virtual void __thiscall MyBase :: PrintStartMessage(void)(?PrintStartMessage @ MyBase @ 1> C:\Users\Shmuelian\Documents\Visual Studio 2008\Projects\s1\Debug\s1.exe:fatal error LNK1120:1 unresolved externals
1> s1 - 2错误0 b警告b
我想强制所有派生类...
A-实现它
B-在它们的构造函数中调用
我该怎么办呢?
解决方案
有很多文章解释为什么你不应该在C ++中的构造函数和析构函数中调用虚函数。查看此处和这里详细说明在这样的调用期间场景后面发生了什么。
I have a base class MyBase that contains a pure virtual function:
void PrintStartMessage() = 0
I want each derived class to call it in their constructor
then I put it in base class(MyBase
) constructor
class MyBase
{
public:
virtual void PrintStartMessage() =0;
MyBase()
{
PrintStartMessage();
}
};
class Derived:public MyBase
{
public:
void PrintStartMessage(){
}
};
void main()
{
Derived derived;
}
but I get a linker error.
this is error message :
1>------ Build started: Project: s1, Configuration: Debug Win32 ------
1>Compiling...
1>s1.cpp
1>Linking...
1>s1.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall MyBase::PrintStartMessage(void)" (?PrintStartMessage@MyBase@@UAEXXZ) referenced in function "public: __thiscall MyBase::MyBase(void)" (??0MyBase@@QAE@XZ)
1>C:\Users\Shmuelian\Documents\Visual Studio 2008\Projects\s1\Debug\s1.exe : fatal error LNK1120: 1 unresolved externals
1>s1 - 2 error(s), 0 warning(s)
I want force to all derived classes to...
A- implement it
B- call it in their constructor
How I must do it?
解决方案
There are many articles that explain why you should never call virtual functions in constructor and destructor in C++. Take a look here and here for details what happens behind the scene during such calls.
这篇关于从基类构造函数调用纯虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文