【发布时间】:2014-01-21 13:36:03
【问题描述】:
我正在尝试创建一个包含虚函数的类,我想在两个子类中继承它。
我知道有些人已经问过这个问题(例如here 和there),但我无法理解答案。
所以我做了一个我正在尝试的简化示例代码:
//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()
我做错了什么?
(对不起,如果我犯了一些英语错误,我不是母语人士)。
【问题讨论】:
-
您没有在子类中覆盖纯虚函数 getName()。
-
你需要在你的子类中实现getName()函数。
-
为什么 getName() 是纯的?
-
在 OOP 世界中,孩子并没有真正从母亲那里继承。
-
包含守卫的名称使用保留标识符,stackoverflow.com/questions/228783/…
标签: c++ class inheritance virtual