预期 class-名称在“{”标记之前 - 带有头文件和 cpp 文件

expected class-name before '{' token - with header files and cpp files

就像很多人问这个问题一样,我对 C++ 很陌生,我无法解决这个错误:

Dollar.h:4:31: error: expected class-name before '{' token
    class Dollar: public Currency {

这些是我的文件

main.cpp

#include <iostream>
#include "Dollar.h"

using namespace std;

int main() {
    Dollar * d = new Dollar();
    d->printStatement();
    return 0;
}

Currency.cpp

#include <iostream>
#include "Currency.h"

using namespace std;

class Currency {
    public:
        virtual void printStatement() {
            cout << "I am parent";
        }
};

Currency.h

#ifndef CURRENCY_H
#define CURRENCY_H

class Currency {
    public:
        virtual void printStatement();
};

#endif

Dollar.cpp

#include <iostream>
using namespace std;

void printStatement() {
    cout << "I am dollar";
}

Dollar.h

#ifndef DOLLAR_H
#ifndef DOLLAR_H

class Dollar : public Currency {
    public:
        void printStatement();
};

#endif

非常感谢您的宝贵时间,非常感谢您的帮助。

错误表明 class 的名称应介于 : public{ 之间:

class Dollar : public Currency {
                      ^^^^^^^^

Currency不是class的名字,因为你还没有定义这样的class。是的,您在文件 Currency.cppCurrency.h 中定义了这样的 class,但没有在发生该错误的文件 Dollar.h 中定义。

解决方法: class Currency 必须先定义,然后才能用作基础 class。像这样:

// class is defined first
class Currency {
    public:
        virtual void printStatement();
};

// now Currency is a class and it can be used as a base
class Dollar : public Currency {
    public:
        void printStatement();
};

由于 class 必须在所有使用它的源文件中定义,并且所有源文件中的定义必须相同,因此在单独的文件中定义 class 通常很有用"header" 文件,如你所做。在这种情况下,您可以简单地包含 header 而不是在每个源文件中重复编写定义:

#include "Currency.h"

Currency.cpp 包含 class Currency 的两个定义。一次在包含的 header 中,然后是第二次。您不能在单个源文件中对同一个 class 进行多个定义。

解决方案:从 Currency.cpp 中删除 class 定义。而是只定义成员函数:

void Currency::printStatement() {
    //...
}

最后,你还没有定义Dollar::printStatement。您已经定义了 printStatement,这不是一回事。