tro*_*guy 2 c++ virtual inheritance class
我正在尝试创建一个包含虚函数的类,我想在两个子类中继承它.
我知道有些人已经问过这个(例如这里和那里),但我无法理解答案.
所以我做了一个我正在尝试的简化示例代码:
//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;
}
Run Code Online (Sandbox Code Playgroud)
这是我的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;
}
Run Code Online (Sandbox Code Playgroud)
这是compilator所说的:( 用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()
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么 ?
(对不起,如果我犯了一些英语错误,我不是母语人士).
在Mother你的宣言中你有:
virtual std::string getName() = 0;
Run Code Online (Sandbox Code Playgroud)
这不仅仅是一个virtual,而是一个纯粹的 virtual.a virtual和pure 之间的区别在于,即使您在基类中提供了实现,virtual纯类还必须在派生类中实现重写.例如:
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
}
Run Code Online (Sandbox Code Playgroud)
您无法使用未实现的纯virtual方法实例化类.如果您尝试,您将收到编译器错误:
int main()
{
Foo f; // ERROR
Bar b; // OK
}
Run Code Online (Sandbox Code Playgroud)
这正是你想要做的.你声明getName()是纯粹 virtual的
Mother,但你没有覆盖它Child.然后你试图实例化一个Child
int main()
{
Child l("lol");
Run Code Online (Sandbox Code Playgroud)
这导致编译器错误.
要修复它,请getName()在Child类中提供覆盖.
| 归档时间: |
|
| 查看次数: |
11362 次 |
| 最近记录: |