就像很多人问这个问题一样,我对 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.cpp
和 Currency.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/