【问题标题】:C++ const struct &variable yields missing tag nameC++ const struct &variable 产生缺少的标签名称
【发布时间】:2012-06-23 19:03:21
【问题描述】:

尝试如下初始化和设置类:

class Accel
{
public:
    Accel(const struct &F, const struct &m, const struct &M, const struct &I);

    etc...
}

当我尝试编译时,我得到“'struct': missing tag name”。我正在使用其他人(我信任的人)的编码“约定”,这是“const struct &...”的来源,但如果有人知道更好的方法,请告诉我。

【问题讨论】:

    标签: c++ struct constants


    【解决方案1】:

    struct 是 C++ 中的关键字;它不能用作类型名称。改用其他东西:

    class Dennis;
    struct Janet;  // "struct" is pretty much identical to "class"
    
    class Accel
    { 
    public:
        Accel(const Dennis & F, const Dennis & m, const Janet & j) { /* ... */ }
        // ...
    };
    

    (C++ 中的类型命名不同于其他语言,例如 C。在 C++ 中你说 class Dennis; Dennis x;,而在 C 中你必须说 struct Janet; struct Janet y;,或者使用 typedef 来创建一个类型名不用说“struct”就可以使用。)

    【讨论】:

    • 我已将 F、m、M 和 I 声明为双精度结构(在其他地方)。所以如果我用“double”代替“struct”会发生什么?例如,F 包含三个双精度数 - Fx、Fy、Fz。
    • @user1187621:没有所谓的“双打结构”。您的实际类型 有一个正确的名称。寻找它,并使用它。 C++ 中没有匿名结构。
    • @user1187621,如果我理解正确 (struct F {double Fx; double Fy; double Fz;};),您的声明中需要 const F &,定义中需要 const F &parameterName
    【解决方案2】:
    const struct &F
    

    这里的F 是什么类型? struct 不是类型(在 C++ 中也不需要该限定符)。我相信你想要一些类似的东西:

    struct Foo {};
    
    class Accel
    {
    public:
        Accel(const Foo &f, ...);
    };
    

    在声明struct 类型的变量时,C 需要struct 关键字,但即便如此,您也不能简单地省略类型名称。通常(在 C 中)你会 typedef struct 以避免在任何地方输入 struct

    typedef struct {
        char *whatever;
    } my_struct;
    
    int main() {
        my_struct s;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 2013-11-18
      • 2017-02-16
      • 2015-10-18
      • 2016-01-09
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多