的左侧应为结构.或.*,但它是一个结构

structure expected on left side of . or .* but it is a structure

本文关键字:结构 一个      更新时间:2023-10-16

我在chest.contents[0]上得到了编译错误structure required on left side of . or .*,但chest是一个结构:

class Item {
public:
    int id;
    int dmg;
};
class Chest {
public:
    Item contents[10];
};
int main() 
{
    Chest chest();
    Item item = chest.contents[0];
    return 0;
}

不是,它是一个零参数的函数。

要默认初始化变量,请使用

Chest chest;

在C++11中,此语法可用于值初始化。

Chest chest{};

在C++03中,这需要一个复杂的(因为许多编译器错误(解决方法,谢天谢地,Boost库使其易于使用:

boost::value_initialized<Chest> chest;
Chest chest();

并不像你可能相信的那样,调用构造函数

Chest::Chest();

而是函数的声明。创建chest的正确方法是

Chest chest;

只有当您定义了接受参数的构造函数时,才应该使用括号。

string s;
string s2("Hello");