我正在尝试学习c++,却在试图弄清楚继承时偶然发现一个错误。

编译:daughter.cpp
在/home/jonas/kodning/testing/daughter.cpp中包含的文件中:1:
/home/jonas/kodning/testing/daughter.h:6:错误:“{” token 之前的预期类名
进程以状态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;
}

mother.cpp:
#include "mother.h"
#include "daughter.h"

#include <iostream>

using namespace std;


mother::mother()
{
    //ctor
}


void mother::saywhat() {

    cout << "WHAAAAAAT" << endl;


}

mother.h:
#ifndef MOTHER_H
#define MOTHER_H


class mother
{
    public:
        mother();
        void saywhat();
    protected:
    private:
};

#endif // MOTHER_H

daughter.h:
#ifndef DAUGHTER_H
#define DAUGHTER_H


class daughter: public mother
{
    public:
        daughter();
    protected:
    private:
};

#endif // DAUGHTER_H

和daughter.cpp:
#include "daughter.h"
#include "mother.h"

#include <iostream>

using namespace std;


daughter::daughter()
{
    //ctor
}

我要做的是让女儿继承母类(= saywhat())公开的所有内容。我究竟做错了什么?

最佳答案

您忘了在此处添加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

您需要包括此 header ,因为daughter是从mother派生的。因此,编译器需要知道mother的定义。

07-24 14:04