c++ - '{' token 之前的预期类名 - 带有头文件和 cpp 文件

标签 c++ inheritance polymorphism header-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;
}

货币.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

美元.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

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

最佳答案

错误表明类名应在 : public{ 之间:

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

Currency 不是类的名称,因为您尚未定义此类。是的,您已在文件 Currency.cppCurrency.h 中定义此类,但未在发生该错误的文件 Dollar.h 中定义.

解决方案:必须先定义类Currency,然后才能将其用作基类。像这样:

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

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

#include "Currency.h"

Currency.cpp 包含类 Currency 的两个定义。一旦包含在标题中,然后第二次。您不能在单个源文件中为同一类定义多个。

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

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

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

关于c++ - '{' token 之前的预期类名 - 带有头文件和 cpp 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48273255/

相关文章:

java - Sub 在其自己的字段成员上使用 super 的实例方法

c++ - 从基类的特定派生类型调用特定函数

c++ - 迭代 C++ std::map 的正确方法不起作用

c++ - 如何将 wchar 值存储在双引号字符串中

c++ - 对象的销毁是否正确发生?

java - java类存储在数据库的哪里?

c++ - 创建简单链表时无法访问内存

c# - 处理类继承自抽象类和类型参数

C++ 多态性/指针 - 表达式必须具有常量值

java - 参数多态性和子类型多态性之间的概念区别?