【问题标题】:Type def struct C objective to C++Typedef struct C 目标到 C++
【发布时间】:2013-11-18 19:14:32
【问题描述】:

我想知道如何将目标 C 中的“typedef struct”转换为 c++ 代码,最好将其转换为类。是否可以 ?我可以使用类吗?

例子:

typedef struct{
    int one;
    int two;
}myStruct;

【问题讨论】:

    标签: c++ class struct typedef


    【解决方案1】:

    C++ 中structclass 之间没有根本区别*。这是具有两个公共数据成员的 mystruct 类型:

    struct mystruct {
        int one;
        int two;
    };
    

    这与

    完全一样
    class mystruct
    {
      public:
        int one;
        int two;
    };
    

    * 不同之处在于成员和基类默认在struct 中是公共的,而在class 中是私有的。这两个关键字可以用来表示相同的类型。

    【讨论】:

    • 默认访问器有区别
    • @ThePlatypus 对,没有根本区别。例如,编译器不会知道class Foo { int i; };struct Foo { private: int i; }; 之间的区别。
    • @juanchopanza 对不起,错过了这个词。
    • 用更好的答案打败我,点个赞:)。如果 OP 或其他人不清楚,c++ class 类型的成员默认为 PRIVATE,而struct 成员默认为 PUBLIC。
    • @BaylesJ 谢谢,你让我意识到我搞砸了脚注中的解释。现在已经解决了。
    【解决方案2】:

    首先,所有关于阅读一些 C++ 好书的标准内容都适用。

    在 C++ 中,结构是类,唯一的区别是类成员的默认可见性并且这些对象不需要 typedef,myStruct 可以自动使用,就像您对它进行 typedef'd 一样。因此,您将拥有:

    struct myStruct {
        int one;
        int two;
    };
    

    并且您可以在此之上添加成员函数和所有这些。普通旧数据 (POD) 结构在 C++ 中也很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      相关资源
      最近更新 更多