C++结构和"error: ISO C++ forbids declaration of '...' with no type"

C++ Struct and "error: ISO C++ forbids declaration of '...' with no type"

本文关键字:C++ with type no of forbids 结构 error ISO declaration      更新时间:2023-10-16

我正在尝试用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 version 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++ Tutorial: Struct中的代码非常相似。

对其他关于"error: ISO c++禁止声明'…' with no type ' (比如这样)建议添加命名空间,但我发现很难看出它在这里不起作用的原因。

总之,我有以下几个问题:
  1. 在这种情况下,这个错误实际上意味着什么?
  2. 这个错误通常意味着什么?
  3. 为什么这个代码不能工作?
  4. 如何使其工作?

如果有人能给我一个答案,和/或一个研究/阅读方向,我将不胜感激。

此代码

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++无法找到类型,因此只需指定类型即可。

在我的例子中,我只能在添加forward声明后解决它。

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;

编译器假定你想声明名为' poss .x'和' poss .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.
    }
}

有些人可能会说这是多余的。很可能是,我不知道你最后的问题到底有多复杂。如果你也不确定,使用类可能是最安全的。

类的全部意义在于数据封装。不要暴露任何不必要的东西,这样您就不必担心其他代码会以您意想不到的方式更改值。使用结构体可能就足够了,但如果不是这样,返回并从结构体转换为类可能比现在直接使用类要困难得多。