请解释以下C ++类定义

时间:2013-09-15 08:24:37

标签: c++ constructor

class A {
public:
    A (int n = 0) : m_n(n) {}
    A (const A& a) : m_n(a.m_n) {}
private:
    int m_n;
}

或:

namespace std {
    template <class T1, class T2>
    struct pair {
        //type names for the values
        typedef T1 first_type;
        typedef T2 second_type;
        //member
        T1 first;
        T2 second;
        /* default constructor - T1 () and T2 () force initialization for built-in types */
        pair() : first(T1()), second(T2()) {}
        //constructor for two values
        pair(const T1& a, const T2& b) : first(a), second(b) {}
       //copy constructor with implicit conversions
        template<class U, class V>
        pair(const pair<U,V>& p) : first(p.first), second(p.second) {}
    };
    ....
}

我不理解这两个类的构造函数,复制构造函数。 请解释一下“:m_n(n)”部分的作用是什么?

1 个答案:

答案 0 :(得分:1)

A (int n = 0) : m_n(n) {}
//           ^^^^^^^^^^

它被称为成员初始化列表

  

在类的构造函数的定义中,它为直接和虚拟基础子对象和非静态数据成员指定初始化器。

例如:

A (int n = 0) : m_n(n) {}

此处,A类的构造函数使用m_n初始化n

看看here

相关问题