我正在尝试学习c ++,我在试图找出继承时偶然发现了一个错误.
编译:daughter.cpp在/home/jonas/kodning/testing/daughter.cpp:1中包含的文件:/home/jonas/kodning/testing/daughter.h:6:错误:'{'令牌之前的预期类名进程终止,状态1(0分,0秒)1个错误,0个警告
我的文件:main.cpp:
#include "mother.h"
#include "daughter.h"
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
mother mom;
mom.saywhat();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
mother.cpp:
#include "mother.h"
#include "daughter.h"
#include <iostream>
using namespace std;
mother::mother()
{
//ctor
}
void mother::saywhat() {
cout << "WHAAAAAAT" << endl;
}
Run Code Online (Sandbox Code Playgroud)
mother.h:
#ifndef MOTHER_H
#define MOTHER_H
class mother
{
public:
mother();
void saywhat();
protected:
private:
};
#endif // MOTHER_H
Run Code Online (Sandbox Code Playgroud)
daughter.h:
#ifndef DAUGHTER_H
#define DAUGHTER_H
class daughter: public mother
{
public:
daughter();
protected:
private:
};
#endif // DAUGHTER_H
Run Code Online (Sandbox Code Playgroud)
和daughter.cpp:
#include "daughter.h"
#include "mother.h"
#include <iostream>
using namespace std;
daughter::daughter()
{
//ctor
}
Run Code Online (Sandbox Code Playgroud)
我想做的是让女儿从母班继承一切公开(= saywhat()).我究竟做错了什么?
Naw*_*waz 25
你忘了在mother.h
这里包括:
#ifndef DAUGHTER_H
#define DAUGHTER_H
#include "mother.h" //<--- this line is added by me.
class daughter: public mother
{
public:
daughter();
protected:
private:
};
#endif // DAUGHTER_H
Run Code Online (Sandbox Code Playgroud)
您需要包含此标头,因为daughter
它源自mother
.所以编译器需要知道它的定义mother
.
与 OP 的问题无关,但对于任何其他 C++ 学习者绊倒这个问题,我因不同的原因收到此错误。如果您的父类是模板化的,则需要在子类中指定类型名称:
#include "Parent.h"
template <typename ChildType>
class Child : public Parent<ChildType> { // <ChildType> is important here
};
Run Code Online (Sandbox Code Playgroud)
在daughter.cpp中,切换两行include.即
#include "mother.h"
#include "daughter.h"
Run Code Online (Sandbox Code Playgroud)
发生了什么是编译器正在研究类的定义,daughter
并且找不到基类的定义mother
.所以它告诉你"我期待mother
在行中"{"前面的标识符
class daughter: public mother {
Run Code Online (Sandbox Code Playgroud)
成为一个班级,但我找不到它的定义!"
在mother.cpp
,删除包含daughter.h
.编译器不需要知道定义daughter.h
; 即mother
可以不使用类daughter
.添加包含会daughter.h
在类定义之间引入不必要的依赖关系.
另一方面,在类(.cpp)的定义中保持包含头而不是类(.h)的声明总是更好的恕我直言.这样,当包含标题时,您不太可能需要解决标题包含的噩梦,而标题又包含您无法控制的其他标题.但是许多生产代码包括标题中的标题.两者都是正确的,当你这样做时需要小心.
检查#ifndef
并#define
在您的头文件中是唯一的。
#ifndef BASE_CLIENT_HANDLER_H
#define BASE_CLIENT_HANDLER_H
#include "Threads/Thread.h"
class BaseClientHandler : public threads::Thread {
public:
bool isOn();
};
#endif //BASE_CLIENT_HANDLER_H
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56757 次 |
最近记录: |