c++ - C++ 中正确的 typedef 位置

标签 c++ typedef

<分区>

请问typedef在C++中的正确​​位置

版本 1:类外类型定义

typedef std::pair<std::string, int> StrIntPair;
typedef std::vector<StrIntPair> StrIntPairVec;

class MyData
{
public:
    MyData(){};
    ~MyData(){};
private:
    void addInfo(const StrIntPair &info)
    {
        infoVec.push_back(info);
    }
    StrIntPair info;
    StrIntPairVec infoVec;
};

Version2 : typedef inside class public

class MyData
{
public:
    MyData(){};
    ~MyData(){};
    typedef std::pair<std::string, int> StrIntPair;
    typedef std::vector<StrIntPair> StrIntPairVec;
private:
    void addInfo(const StrIntPair &info)
    {
        infoVec.push_back(info);
    }
    StrIntPair info;
    StrIntPairVec infoVec;
};

Version3 : typedef inside class private

class MyData
{
public:
    MyData(){};
    ~MyData(){};
private:
    typedef std::pair<std::string, int> StrIntPair;
    typedef std::vector<StrIntPair> StrIntPairVec;
    void addInfo(const StrIntPair &info)
    {
        infoVec.push_back(info);
    }
    StrIntPair info;
    StrIntPairVec infoVec;
};

哪个版本是最佳实践?

最佳答案

这取决于您在哪里使用类型别名。我建议你

  • 如果您跨类和/或函数使用它们并且别名的含义不仅仅与类相关,则将它们放在类之外。
  • 如果类外的客户端代码需要访问它们(例如初始化对象或存储成员函数的别名返回值)但别名与类相关,则将它们定义为公共(public)类类型别名。然后别名成为类接口(interface)的一部分。
  • 当您在类中专门使用它们时,将它们定义为私有(private)类类型别名,例如一些实用数据结构,在跨成员函数传递它时总是烦人地输入它。

编译器只会强制执行范围太窄的别名(例如,您使用在该类之外的类的私有(private)部分中定义的类型别名)并且如果您选择不必要的许可范围(例如,您公开声明别名,但仅在类实现中使用它)。因此,尽量选择尽可能窄的范围,这符合隐藏实现细节的要求。

作为旁注,您可能需要考虑使用 using StrIntPair = std::pair<std::string, int>; 声明您的类型别名,请参阅 Effective Modern C++ 中的第 9 项。不过,这对上述内容没有影响。

关于c++ - C++ 中正确的 typedef 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52072494/

相关文章:

溢出后 C++ 差异正确

具有默认参数的 C++ 模板

c - typedef 可见性

c++ - 在派生类中重新定义 typedef?

c++ - 在基类中引用不同大小的 std::array 而不是 std::array

c++ - C 的 C++ 文件中的正确前向定义包括

c++ - Visual Studio - 获取字符串中第一个字符的内存地址

c++ - 如何从线程中取回数据?

c - 跟踪函数调用

时间:2019-03-08 标签:c++typedefgenerics