初始化struct的Const变量

时间:2015-05-28 15:38:14

标签: c++ data-structures struct

看了几个其他问题和答案,但我似乎无法弄清楚如何将它应用到我的情况中。

这是我的设置:

import random
try:
    x = input("How many rounds: ")
    rounds = 0
    while rounds < int(x):
        # rock=0, paper=1, scissors=2
        computer1 = random.randint(0,2)
        computer2 = random.randint(0,2)

        if computer1 == computer2:
            print ("draw")
        elif computer1 == 0 and computer2 == 1:
            print ("lose")
        elif computer1 == 1 and computer2 == 2:
            print ("lose")
        elif computer1 == 2 and computer2 == 0:
            print ("lose")
        else:
            print ("win")
        rounds = rounds + 1
except (ValueError):
    print('Wrong input')

从我读过的内容来看,下面的代码似乎是一种可能的解决方案,但我并不接近我的编译器,所以我无法测试。那看起来不错吗?如果错了,你能提供解决方案吗?

typdef struct sensor {
    const unsigned char pin;

    //otherVariables
}Sensor;

Sensor *left = new Sensor();

void initStruct() {
    left->pin = 1; //illegal initialization
}

2 个答案:

答案 0 :(得分:2)

除非有奇怪的事情发生,否则你不需要动态分配。如果类型是聚合,那么您可以在声明中简单地初始化它:

Sensor left = {1 /*, other variables */};

如果它不是聚合,则必须在构造函数中初始化const成员:

struct Sensor {
    const unsigned char pin;
    //otherVariables

    Sensor(unsigned char pin) : pin(pin)
        //, other variables
    {}
};

(我冒昧地删除了奇怪的C风格typedef。在C ++中,这只是毫无意义的噪音。)

答案 1 :(得分:0)

没有那段代码没有意义。

  1. pin成员为const,因此除初始化程序外,您无法分配给该成员。

  2. pin成员,不是指针,因此malloc()无法正确编译。

  3. 我认为您需要从const字段中删除struct,这根本没有任何意义。如果您想防止意外修改它,请创建struct实例const,而不是成员。

相关问题