码迷,mamicode.com
首页 > 编程语言 > 详细

C++ Constructor

时间:2015-08-11 09:55:57      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

// File: test.cpp
// Author: lxw
// Date: 2015-08-11

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <climits>

using namespace std;

int number(){
    cout << "hello" << endl;
    return 11;
}

class Demo{
private:
    int a = number();   //NOTE: [calls before constructor.] NOT ALWAYS call this.
    int b = number();
public:
    Demo(){
        cout << "Constructor Demo()" << endl;
    }
    Demo(int A):a(A){
        cout << "Constructor Demo(int A)" << endl;
    }
    int getA(){
        return this->a;
    }
    int getB(){
        return this->b;
    }
};

int main(void){
    /*
    //NOTE: NOT "hello\nConstructor Demo(int A)" but "Constructor Demo(int A)"
    Demo d(3);  //Constructor Demo(int A)
    cout << d.getA() << endl; //3    
    cout << endl;
    Demo d1;  //hello\nConstructor Demo()
    cout << d1.getA() << endl;  //11
    */
    /*
    Output:
    Constructor Demo(int A)
    3

    hello
    Constructor Demo()
    11
    */

    Demo d(3);  //hello\nConstructor Demo(int A)
    cout << d.getA() << endl; //3
    cout << d.getB() << endl; //11
    cout << endl;
    Demo d1;  //hello\nhello\nConstructor Demo()
    cout << d1.getA() << endl;  //11
    cout << d1.getB() << endl;  //11
    /*
    Output:
    hello
    Constructor Demo(int A)
    3
    11

    hello
    hello
    Constructor Demo()
    11
    11
    */
    return 0;
}

 

C++ Constructor

标签:

原文地址:http://www.cnblogs.com/lxw0109/p/cpp_constructor.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!