我正在尝试创建一个包含虚函数的类,我想在两个子类中继承该虚函数。
我知道有人已经问过这个问题(例如,在这里和那里),但是我听不懂答案。
所以我做了一个简化的示例代码,我正在尝试:
//Mother .h file
#ifndef _MOTHER_H_
#define _MOTHER_H_
#include <iostream>
class Mother
{
protected :
std::string _name;
public:
Mother(std::string name);
~Mother();
virtual std::string getName() = 0;
};
#endif
//Mother .cpp file
#include "Mother.h"
Mother::Mother(std::string name)
{
this->_name = name;
}
Mother::~Mother()
{
}
//Child.h file
#ifndef _CHILD_H_
#define _CHILD_H_
#include "Mother.h"
class Child : public Mother
{
private :
std::string _name;
public:
Child(std::string name);
~Child();
};
#endif
//Child .cpp file
#include "Mother.h"
#include "Child.h"
Child::Child(std::string name) : Mother(name)
{
this->_name = name;
}
Child::~Child()
{
}
std::string Mother::getName()
{
return this->_name;
}
这是我的main.cpp文件:
//Main.cpp file
#include "Child.h"
int main()
{
Child l("lol");
std::cout << l.getName() << std::endl;
Mother& f = l;
std::cout << f.getName() << std::endl;
return 0;
}
编译器的说明如下:(使用g ++ * .cpp -W -Wall -Wextra -Werror进行编译)
main.cpp: In function ‘int main()’:
main.cpp:5:9: error: cannot declare variable ‘l’ to be of abstract type‘Child’
In file included from main.cpp:1:0:
Child.h:8:7: note: because the following virtual functions are pure within ‘Child’:
In file included from Child.h:6:0,
from main.cpp:1:
Mother.h:14:23: note: virtual std::string Mother::getName()
我究竟做错了什么 ?
(对不起,如果我在英语方面犯了一些错误,我不是母语人士)。
在Mother
的声明中,您有:
virtual std::string getName() = 0;
这不仅仅是一个virtual
,而是一个纯粹的 virtual
。avirtual
和pure 的区别在于,即使您已经在基类中提供了实现,virtual
pure品种也必须具有在派生类中实现的重写。例如:
class Foo
{
public:
virtual void DoIt() = 0 {}; // pure virtual. Must be overridden in the derived class even though there is an implementation here
};
class Bar : public Foo
{
public:
void DoIt(); // override of base
};
void Bar::DoIt()
{
// implementation of override
}
您无法使用未实现的纯virtual
方法实例化类。如果尝试,将出现编译器错误:
int main()
{
Foo f; // ERROR
Bar b; // OK
}
而这正是您尝试做的。您声明getName()
是纯净 virtual
的Mother
,但您没有在中覆盖它Child
。然后您尝试实例化一个Child
int main()
{
Child l("lol");
这导致了编译器错误。
要解决此问题,请getName()
在Child
类中提供重写。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句