24

我对 C++ 比较陌生(所以请尽量保持简单的答案!),我不明白为什么会出现错误:C++ requires a type specifier for all declarations whilst defining methods.

我正在尝试编写一个简单的程序来逐行读取文本文件,将值存储到数组中。但是,当我尝试在 .cpp 文件中声明方法时遇到问题。请在下面找到代码。

字符串列表.h

#ifndef StringListH
#define StringListH

#include <vector>
#include <string>

class StringList {
public:
     StringList();
     ~StringList();
     void PrintWords();
private:
     size_t numberOfLines;
     std::vector<std::string> str;
};

#endif

字符串列表.cpp

#include "StringList.h"
#include <fstream>
#include <istream>
#include <algorithm> // std::copy
#include <iterator>  // istream_iterator

using namespace std;

StringList::StringList()
{
    ifstream myfile("input.in");
    if (myfile.is_open())
    {
        copy(
            istream_iterator<string>(myfile),
            istream_iterator<string>(),
            back_inserter(str));
    }
    numberOfLines = str.size();
}

StringList::~StringList(){
    //Deconstructor
}

// Error Happens Here
StringList::PrintWords(){
    //Print My array
}

我用谷歌搜索无济于事,我不太明白如何阅读 C++ 的正确文档,所以我有点卡住了。到目前为止,我已经编写了大约 3 或 4 个(简单)面向对象的程序,但我从来没有遇到过这个问题。如果它有帮助,我正在使用 Xcode,但我在 eclipse 中遇到了同样的错误。

似乎任何方法,无论返回类型、名称、我的头文件中定义的参数如何,都会出现此错误 - 但是构造函数很好。如果 PrintWords() 被删除,项目构建就好了。

任何指针将不胜感激!

4

3 回答 3

31

您将其声明为,void但忘记将其放入定义中。应该:

void StringList::PrintWords()

于 2013-11-05T22:14:25.060 回答
6

您的成员函数PrintWords原型为:

void PrintOn();

意味着它返回void。当你在别处实现你的函数时,你仍然需要提供返回类型,你错误地忽略了它:

/* void */ StringList::PrintOn() { ... }
于 2013-11-05T22:13:49.563 回答
5

void在给你问题的行前面放一个。

即使感觉多余,您也必须在声明和实现中指定返回类型。

于 2013-11-05T22:13:41.510 回答