基类未定义。错误C2504

问题描述:

按照本教程(https://www.youtube.com/watch?v=gq2Igdc-OSI&index=52&list=PLAE85DE8440AA6B83),我在Visual Studio C++ 2017上遇到了4个错误。其中3个是相同的,只是在daughter.h文件中重复'Mother':base class undefined。另一个错误是:'sayName'不是'女儿'的成员现在,这里是代码。这是非常简单的,我希望程序打印...我希望它打印出两行“你在那里做什么?”如果你能帮我解答这个问题,那会很棒。谢谢。 对于主文件 `的#include “stdafx.h中” 的#include 的#include “Daughter.h” 的#include “Mother.h” 使用命名空间std;基类未定义。错误C2504

int main() 
{ 
    Mother pot; 
    pot.sayName(); 
    Daughter kettle; 
    kettle.sayName(); 
    int pause = 0; 
    cin >> pause; 
} 

Mother.h 
#ifndef MOTHER_H 
#define MOTHER_H 

class Mother 
{ 
public: 
    Mother(); 
    void sayName(); 

}; 

#endif 
Mother.cpp 
#include "stdafx.h" 
#include<iostream> 
#include"Daughter.h" 
#include"Mother.h" 
using namespace std; 

Mother::Mother() 
{ 
} 
void Mother::sayName() { 
    cout << "What are you doing there?" << endl; 

} 
Daughter.h 
#ifndef DAUGHTER_H 
#define DAUGHTER_H 

class Daughter:public Mother 
{ 
public: 
    Daughter(); 
}; 
#endif 
Daughter.cpp 
#include "stdafx.h" 
#include<iostream> 
#include"Daughter.h" 
#include"Mother.h" 
using namespace std; 

Daughter::Daughter() 
{ 
} 
+0

将'#include“Mother.h”'移到Daughter.h。 – GAVD

当一个类继承另一个类时,它的头中必须包含父类头。在你的情况下,你必须在女儿头顶部添加#include "Mother.h"(不仅在.cpp文件中)。另一个错误是由于第一个错误而发生的,并且纠正它应该解决它。

当您编写继承语法class Daughter : public Mother时,Daughter类定义需要访问有关其父类的信息,原因有几个。其中之一是有关继承方法的信息,这是导致你的第二个错误。

+0

非常感谢您帮助我解决问题。这是适用于所有Visual Studio项目吗?我问这是因为我看过的教程(https://www.youtube.com/watch?v=gq2Igdc-OSI&index=52&list=PLAE85DE8440AA6B83)没有这样做。 –

+0

@DarkChocolate我查了一下,甚至还有一些关于这个问题的评论。此外,这适用于您要编写的所有C++代码(即使不在Visual Studio中)。 –

+1

再次感谢您帮助我解决问题。 –