C++ 为什么我不能在结构中对变量进行算术运算或强制转换?

C++ Why can't I do arithmetic with, or cast variables in a struct?

我有一个游戏,我想计算一个玩家在电脑上玩剪刀石头布的输赢(C++的随机数函数)。为了跟踪玩家的胜负和与计算机的平局,我创建了这个结构(这是全局的):

struct human{
    short wins = 0;
    short losses = 0;
    short ties = 0;
};

当我尝试使用结构中的 short 变量之一进行数学计算时出现问题:

int main(){
    short totalPlays = 1;
    float winsPerc;
    outcome(totalPlays, winsPerc);
}
void outcome(short totalPlays, float& winsPerc){
    winsPerc = (static_cast<float>(human.wins) / static_cast<float>(totalPlays))* 100;
}

在这两个函数中,我试图计算玩家获胜的百分比。但是,我的编译器似乎将 human.wins 变量的 human 部分解释为一种类型。所以当然我尝试将 human.wins 更改为 short human.wins 无济于事。之后编译器只说 short 的类型是意外的。由于这太模糊了,我真的不知道我做错了什么。任何帮助将不胜感激!

您误解了 struct 是什么。您将 struct human 视为一个对象,其中包含您可以使用的数据,但事实并非如此;它是 类型 ,就像 class。其实一个class.

在其成员的发言前随意添加关键字 short 不会有任何效果! (恐怕您的 "of course" 条款毫无意义。)

您必须先实例化该类型,然后才能对其进行操作。在你的情况下有一个简单的 shorthand:

struct {
    short wins = 0;
    short losses = 0;
    short ties = 0;
} human;

现在这是一个未命名的 struct 类型定义,立即实例化为 human

可能导致您感到困惑的是另一个 shorthand 的使用:那些内联成员初始化程序(仅在少数几年内才成为有效语法)。他们说,每当实例化这种类型的对象时,它的所有成员都将被初始化为 0。如果您的代码如下所示,可能会更明显:

struct human_t {
    short wins;
    short losses;
    short ties;
};

human_t human = {0, 0, 0};

只要您的听众了解现代 C++,尽管前面的示例可能没问题。