错误:类中未声明 '' 成员函数

error: no ‘’ member function declared in class ''

本文关键字:成员 函数 未声明 错误      更新时间:2023-10-16

我正在尝试创建一个包含虚函数的类,我想在两个子类中继承该函数。

我知道有些人已经问过这个问题(例如这里和那里),但我无法理解答案。

所以我做了一个简化的示例代码:

//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;
}

这是我的主要.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,而是一个纯粹virtualvirtualvirtual之间的区别在于,纯品种必须在派生类中实现重写,即使您已在基类中提供了实现也是如此。 例如:

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()virtualMother,但您没有在Child中覆盖它。 然后,您尝试实例化Child

int main()
{
Child l("lol");

这导致了编译器错误。

若要修复此问题,请在Child类中提供对getName()的重写。

class child应该重写getName()方法,因为它pure virtualclassmother

对我来说似乎是错字..正如std::string Mother::getName()child.cpp中定义的那样..

std::string Child::getName()
{
return this->_name;
}

从 OOP 的角度来看,基类 Mother 中的纯虚函数没有意义,它是所有孩子的共同特征,因此可以使用相同的函数。没有必要覆盖它。

struct Person
{
Person(std::string name) : _name(name) {}
std::string _name;
std::string getName() {return _name; }
};
struct Mother : Human
{
Mother(std::string name) : Person(name) {}
};
struct Child : Human
{
Child(std::string name) : Person(name) {}
};