使用C++继承时编译错误

0 c++ inheritance

我是这个网站的新手,我在C++中尝试一个简单的继承示例.我检查了很多次代码,我发现它没有任何问题,但编译器给了我错误:

我的代码:

#ifndef READWORDS_H
#define READWORDS_H
using namespace std;
#include "ReadWords.h"

/**
 * ReadPunctWords inherits ReadWords, so MUST define the function filter.
 * It chooses to override the default constructor.
 */

class ReadPunctWords: public ReadWords {
    public:
    bool filter(string word);
};

#endif
Run Code Online (Sandbox Code Playgroud)

我从编译器得到的消息:

ReadPunctWords.h:11: error: expected class-name before '{' token
ReadPunctWords.h:13: error: `string' has not been declared
ReadPunctWords.h:13: error: ISO C++ forbids declaration of `word' with no type

Tool completed with exit code 1
Run Code Online (Sandbox Code Playgroud)

我真的不确定哪里弄错了,因为它对我来说很好看?感谢您发现的任何错误.

GMa*_*ckG 12

你需要包含字符串:

#include <string>
Run Code Online (Sandbox Code Playgroud)

那说,不要用using namespace!特别是在文件范围内,绝对不在头文件中.现在任何包含此文件的单元都被迫屈服于std命名空间中的所有内容.

拿出来,并确定你的名字:

bool filter(std::string word);
Run Code Online (Sandbox Code Playgroud)

它的可读性也更具可读性.另外,你应该把你的字符串作为const&:

bool filter(const std::string& word);
Run Code Online (Sandbox Code Playgroud)

避免不必要地复制字符串.最后,你的头部护卫似乎关闭了.他们应该改变吗?截至目前,它们看起来与您的其他标题中使用的相同,可能会有效地阻止它被包含在内.

如果你定义READWORDS_H然后包含ReadWords.h,如果还有:

#ifndef READWORDS_H
#define READWORDS_H
Run Code Online (Sandbox Code Playgroud)

然后将处理该文件中的任何内容.如果是这种情况,ReadWords因为不会定义类,也不能继承它.你的警卫应该是:

READPUNCTWORDS_H
Run Code Online (Sandbox Code Playgroud)