[英]C++ Struct and “error: ISO C++ forbids declaration of '…' with no type”
我试图用C ++编写类和结构:
using namespace std;
struct Position {
int x;
int y;
};
class Maze {
Position pos;
pos.x = 0;
pos.y = 0;
};
int main() {
return 0;
}
但是当我尝试编译它时会出现一些错误:
(gcc版本4.3.2)
10: error: ISO C++ forbids declaration of 'pos' with no type
10: error: expected ';' before '.' token
11: error: ISO C++ forbids declaration of 'pos' with no type
11: error: expected ';' before '.' token
看起来这段代码与C ++教程Struct中的代码几乎相同。
关于“错误:ISO C ++禁止声明无类型的'...'”的其他答案(例如this )建议添加名称空间,但是我很难看到它在这里不起作用的原因是什么。
总而言之,我有以下问题:
如果有人可以给出答案和/或研究/阅读的方向,我将不胜感激。
这段代码
pos.x = 0;
pos.y = 0;
需要一个功能。 一种方法是将其放入构造函数中,例如:
class Maze {
Position pos;
public:
Maze() {
pos.x = 0;
pos.y = 0;
}
};
请注意,我将构造函数公开,否则您将无法使用Maze类
编辑:实际回答您的问题:
在这种情况下,此错误实际上意味着什么? 编译器不知道该如何处理pos.x = 0
因为此时它需要声明,而不是代码。
该错误通常意味着什么? 这通常意味着编译器不知道如何处理您编写的声明。
为什么此代码不起作用? 因为您将可执行代码放在应该放置声明的位置。
如何使其运作? 参见上面的代码。
由于此问题的标题为“ ISO C ++禁止声明没有类型的“东西” ”,因此这是一个更通用的答案。 C ++无法找到类型,因此只需指定类型即可。
就我而言,只有添加前向声明后,我才能解决它。
A.hpp
class A
{
};
B.hpp
#include "A.hpp"
class B
{
public:
A* inst;
};
这导致ISO C ++的错误,禁止无类型的A声明。
因此,我对B.hpp
进行了如下更改:
#include "A.hpp"
class A;//the forward declaration
class B
{
public:
A* inst;
};
它编译良好!
首先,您不能在课程的顶层初始化成员:
class Maze {
Position pos;
pos.x = 0;
pos.y = 0;
};
您必须提供某种构造函数,并且,如果您处于该职位的默认状态下,则可能是您要完成初始化的地方。 对象通常应负责其自身的初始化和拆除:
using namespace std;
struct Position {
int x;
int y;
Position() : x(0), y(0) {}
};
class Maze {
Position pos;
};
int main () {
return 0;
}
第10和11行是
pos.x = 0;
pos.y = 0;
编译器假设您要声明名为“ pos.x”和“ pos.y”的变量,并且抱怨是因为您没有告诉它这些变量的类型。
正如The Dark所建议的那样,要做的是将这两个分配移动到构造函数中。
但是,如果我不确定以后事情会变得多么复杂,我可以这样写:
class Position {
private:
int x;
int y;
public:
Position(int x0, int y0) : x(x0), y(y0) {
// Any other initialization here.
}
inline int getX() { return x; }
inline int getY() { return y; }
inline void setX(int x0) { x = x0; }
inline void setY(int y0) { y = y0; }
}
class Maze : public Position {
Maze() : Position(0,0) {
// Any other initialization here.
}
}
有人会说这太过分了。 很可能,我不知道您最后的问题到底有多复杂。 如果您不确定,也可以选择上课。
类的全部要点是数据封装。 不要暴露任何不必要的东西,这样就不必担心其他代码会以意想不到的方式更改值。 使用一个结构也许就足够了,但是如果不是这样,那么返回并从一个结构转换为一个类可能比现在仅进行一个类要困难得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.