解释错误:ISO C++ 禁止声明没有类型的“Personlist”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7929477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Explain the error: ISO C++ forbids declaration of `Personlist' with no type
提问by Ms01
I have a class which is going to handle an array of objects of another class I've created earlier (which works fine). The problem appears when I try to create an object of my List-class.
我有一个类将处理我之前创建的另一个类的对象数组(工作正常)。当我尝试创建 List 类的对象时出现问题。
This is the header of the list-class:
这是列表类的标题:
#ifndef personlistH
#define personlistH
#include "Person.h"
#include <iomanip>
#include <iostream>
#define SIZE 10
namespace std {
class PersonList {
private:
Person persons[SIZE];
int arrnum;
string filename;
public:
Personlist();
};
}
#endif
This is the main function:
这是主要功能:
#include <iostream>
#include "PersonList.h"
using namespace std;
int main() {
PersonList personlist;
return 0;
}
The error my compiler is giving me is the following:
我的编译器给我的错误如下:
error: "27 \PersonList.h ISO C++ forbids declaration of `Personlist' with no type"
错误:“27 \PersonList.h ISO C++ 禁止声明没有类型的‘Personlist’”
I've searched for answers but as I'm quite new to C++ it's been a bit confusing and I haven't found any fitting yet. It would be great if you could explain this error for me.
我一直在寻找答案,但由于我对 C++ 很陌生,所以有点困惑,我还没有找到任何合适的答案。如果您能为我解释这个错误,那就太好了。
回答by RobH
You have the wrong capitalisation on your constructor declaration. You have Personlist();
but need PersonList();
. Because what you have isn't equal to the class name it is considered a function rather than a constructor, and a function needs a return type.
您的构造函数声明的大小写错误。你有Personlist();
但需要PersonList();
. 因为您拥有的不等于类名,所以它被视为函数而不是构造函数,并且函数需要返回类型。
回答by Alok Save
Do notadd your own types to the standard namespace(std
), instead create your own namespace and define your class inside it.
不要将您自己的类型添加到标准命名空间(std
),而是创建您自己的命名空间并在其中定义您的类。
//PersonList.h
//人员列表.h
namespace PersonNamespace
{
class PersonList
{
//members here
};
}
//Main.cpp
//主.cpp
using namespace PersonNamespace;
The actual error is that you made a typo in Personlist
instead of PersonList
实际的错误是你打错了Personlist
而不是PersonList
回答by Mike Seymour
The error is because you got the capitalisation wrong when you declared the constructor; it should be PersonList()
not Personlist()
.
错误是因为您在声明构造函数时弄错了大小写;应该PersonList()
不是Personlist()
。
Also, you should never declare your own classes in the std
namespace; that's reserved for the standard library. You shoud make up your own namespace name, and put your things in that.
此外,永远不要在std
命名空间中声明自己的类;这是为标准库保留的。您应该创建自己的命名空间名称,并将您的东西放入其中。