深入理解C++11【2】

深入理解C++11【2】

1、继承构造函数。

  当基类拥有多个构造函数的时候,子类不得不一一实现。

  C++98 可以使用 using 来使用基类的成员函数。

#include < iostream> using namespace std; 
struct Base { 
    void f( double i){ 
        cout << "Base:" << i << endl; 
    } 
}; 
struct Derived : Base { 
    using Base:: f; 
    void f( int i) { 
        cout << "Derived:" << i << endl; 
    } 
}; 

int main() { 
    Base b; 
    b. f( 4. 5); // Base: 4. 5 
    
    Derived d; 
    d. f( 4. 5); // Base: 4. 5 
} // 编译 选项: g++ 3- 1- 3. cpp

  C++11中,这个功能由成员函数扩展到了构造函数上。

struct A { 
    A( int i) {} 
    A( double d, int i) {} 
    A( float f, int i, const char* c) {} // ... 
}; 

struct B : A { 
    using A:: A; // 继承 构造 函数 
    // ... 
    virtual void ExtraInterface(){} 
};

  这 意味着 如果 一个 继承 构造 函数 不被 相关 代码 使用, 编译器 不 会为 其 产生 真正 的 函数 代码。

  对于 继承 构造 函数 来讲, 参数 的 默认值不会被继承 的。 事实上, 默认值 会 导致 基 类 产生 多个 构造 函数 的 版本, 这些 函数 版本 都会 被 派生 类 继承。

  如果 一旦 使用 了 继承 构造 函数, 编译器 就不 会 再为 派生 类 生成 默认 构造 函数 了,

struct A { A (int){} }; 
struct B : A{ using A:: A; }; 
B b; // B 没有 默认 构造 函数

  截至2013年,还没有编译器实现了继承构造函数。

2、委派构造函数。

3、

4、

5、

6、

7、

猜你喜欢

转载自www.cnblogs.com/tekkaman/p/10211551.html