【问题标题】:headers and cpp files头文件和 cpp 文件
【发布时间】:2015-10-25 17:41:48
【问题描述】:

我得到了这个超级简单的代码,我正在尝试在 Linux 下编译(第一次在 linux 下工作) 我之前用c++编程过,了解头文件和cpp文件的概念...

句子.h

#ifndef SENTENCE_H_
#define SENTENCE_H_

std::vector<std::string> split(char sentence[]);
void printWords(std::vector<std::string> words);

#endif

句子.cpp

#include "../include/Sentence.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

std::vector<std::string> split(char sentence[]) {
    string str(sentence);
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream

    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

void printWords(std::vector<std::string> words) {
    for (size_t i = 0; i < words.size(); ++i)
           std::cout << words[i] << endl;
}

我遇到了一些我无法弄清楚为什么的错误......

daniel@daniel-ubuntu-server:~/workspace/HW1$ make
g++ -g -Wall -Weffc++ -c -Linclude -o bin/Sentence.o src/Sentence.cpp
In file included from src/Sentence.cpp:1:0:
src/../include/Sentence.h:4:6: error: ‘vector’ in namespace ‘std’ does not name a template type
 std::vector<std::string> split(char sentence[]);
      ^
src/../include/Sentence.h:5:22: error: variable or field ‘printWords’ declared void
 void printWords(std::vector<std::string> words);
                      ^
src/../include/Sentence.h:5:17: error: ‘vector’ is not a member of ‘std’
 void printWords(std::vector<std::string> words);
                 ^
src/../include/Sentence.h:5:29: error: ‘string’ is not a member of ‘std’
 void printWords(std::vector<std::string> words);
                             ^
src/../include/Sentence.h:5:42: error: ‘words’ was not declared in this scope
 void printWords(std::vector<std::string> words);
                                          ^
makefile:10: recipe for target 'bin/Sentence.o' failed
make: *** [bin/Sentence.o] Error 1

【问题讨论】:

  • 想想你的#include指令的顺序。
  • printWords是否需要复制向量才能输出?

标签: c++ file header


【解决方案1】:

您的标头使用 std::vector 类,但向量类代码从未包含在其中。将#include &lt;vector&gt; 添加到头文件中,以便在Sentence.h 的其余部分之前加载该类。

这也有助于其他可能使用 Sentece.h 的文件,因为它们不必自己包含矢量类。

【讨论】:

    【解决方案2】:

    Sentence.h 使用 std::vector 但不包括 &lt;vector&gt; 标头。与std::string 的情况相同。

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 2012-02-12
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多