【问题标题】:error: expected ‘)’ before ... (header file constructor)错误:预期的“)”之前...(头文件构造函数)
【发布时间】:2016-02-09 21:48:54
【问题描述】:

我有这个类字典的头文件

#ifndef DICTIONARY_H
#define DICTIONARY_H

#include <string>
#include <vector>
#include <unordered_set>

class Dictionary {
public:
    Dictionary(string wordFile);
    bool contains(const string& word) const;
    vector<string> get_suggestions(const string& word) const;
private:
    unordered_set<string> words;
};

#endif

我收到错误“错误:预期的构造函数、析构函数或在‘(’令牌 Dictionary::Dictionary(string wordFile)”之前的类型转换。在 .cpp 文件中,它看起来像这样:

#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>
#include "word.h"
#include "dictionary.h"
#include <unordered_set>
#include <string>

Dictionary::Dictionary(string wordFile) {
  string str;
  ifstream input(wordFile);

  while (getline(input, str)) {
    words.insert(str);
  }
}

bool Dictionary::contains(const string& word) const {
  unordered_set<string>::const_iterator got = words.find(word);
  if(got == words.end()){
    return false;
  }
  return true; 
}

vector<string> Dictionary::get_suggestions(const string& word) const {
  vector<string> suggestions;
  return suggestions;
}

我不知道出了什么问题...我来自 Java 背景,在习惯用 C++ 编写和修复这些错误时遇到了一些麻烦。

【问题讨论】:

  • 这是您得到的唯一错误吗?你用using namespace std;吗?
  • 我没有使用命名空间std,但是我编辑了我的代码并在我的头文件中的任何地方添加了范围“std::”,现在我在我的.cpp文件中只得到这个错误:错误: '(' 标记 Dictionary::Dictionary(string wordFile) { 之前的预期构造函数、析构函数或类型转换
  • #include "Dictionary.h"?
  • 已编辑,因此您可以看到整个 .cpp 文件,是的,我包括了头文件
  • 您还需要通过 .cpp 文件并使用 std:: 确定范围

标签: c++11


【解决方案1】:

原来的错误是因为你没有在头文件中限定string

   Dictionary(string wordFile);

应该是:

Dictionary(std::string wordFile);

(对于标题中stringunordered_map 的其他用途也是如此)。

您在 .cpp 文件中也会遇到同样的问题,但您可以通过在文件顶部添加using namespace std;所有#include 指令之后解决它。 (您不应该将using namespace 放在头文件中,或者在包含头文件之前,因为它可能会产生不良后果并混淆后面的头文件。

【讨论】:

  • 做这一切似乎解决了这个问题。我认为包含字符串、unordered_set 等就足够了……但我还必须添加命名空间。傻...非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
  • 2016-03-14
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多