【问题标题】:xcode 7.3: how to put a constant in a structxcode 7.3:如何将常量放入结构中
【发布时间】:2016-07-13 12:47:13
【问题描述】:

我想将常量放入结构中,但编译器生成错误“;”在“=”处丢失。

struct {
    int aaa=111;  // error: "expected ; at end of declaration list"
} blah;

【问题讨论】:

  • 你确定代码至少是用 C++11 编译的吗? (在类成员字段中初始化是 C++11 特性)

标签: c++ ios objective-c iphone xcode


【解决方案1】:

你试过了吗:

int aaa{111};

如果您需要 int 作为常量,您可能应该包含 const 关键字。

const int aaa{111};

【讨论】:

    【解决方案2】:

    在 Obj-C 中定义结构时不能初始化。在创建实例时可以进行初始化,如下所示。

    struct Employee {
      int idNumber;
      int age;
    };
    
    // create instance
    struct Employee emp1;
    emp1.idNumber=12345;
    emp1.age = 25;
    

    【讨论】:

      【解决方案3】:

      如果您使用的是 Objective-C,请在 .h 文件中添加如下内容:

      extern const struct MyStruct {
          int aaa;
      } MyStruct;
      

      .m 文件中:

      const struct MyStruct MyStruct = {
          .aaa = 1
      };
      

      #import .h 文件并在您的代码中使用该结构,如下所示:

      if (someInteger == MyStruct.aaa) ...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 2010-10-15
        • 2017-01-24
        • 1970-01-01
        相关资源
        最近更新 更多