C++コンストラクション関数の3つを深く探求する:コンストラクション関数の委託

8601 ワード

委託コンストラクション関数はc++11の新しい基準に属するため、コンパイル時にコンパイラタイプをc++11と指定する必要がある、linuxは-std=c++11のオプションで指定できる:g++test.cpp-std=c++11-o test 1、依頼コンストラクション関数とはその名の通り、依頼コンストラクション関数は、その属するクラスの他のコンストラクション関数を使用して初期化プロセスを実行します.つまり、そのいくつか(またはすべて)の職責を他のコンストラクション関数に委任します.
class testA
{
    public:
    testA(int ii,double dd):i(ii),d(dd)
    //       
    {
        cout<<"non delegating constructor carried out! 
"
; } testA():testA(0,0) // 1, { cout<<"default constructor carried out!
"
; } testA(string str):testA() // 2, 1 { cout<<"str:"<<str<<endl; } int i; double d; }; testA : , , 。 , , 1 ; , 2

2、関数の実行順序ある関数が別の構造関数に委任されると、委任された構造関数の初期値リストと関数体が一度に実行される.
#include
#include
using namespace std;
class testA
{
    public:
    testA(int ii,double dd):i(ii),d(dd)
    //       
    {
        cout<<"non delegating constructor carried out! 
"
; } testA():testA(0,0) // 1, { cout<<"default constructor carried out!
"
; } testA(string str):testA() // 2, 1 { cout<<"str:"<<str<<endl; } int i; double d; }; int main() { testA A0(11,3.14); testA A1; string str="hello world"; testA A2(str); return 0; } : g++ -std=c++11 test.cpp -o test : non delegating constructor carried out! // A0 non delegating constructor carried out!// A1 default constructor carried out! // non delegating constructor carried out!//A2 1, 1 default constructor carried out! // str:hello world