程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++中組合類的初始化:冒號語法(常數據成員和引用成員的初始化)

C++中組合類的初始化:冒號語法(常數據成員和引用成員的初始化)

編輯:C++入門知識

 

//============================================================================ 

// Name        : main.cpp 

// Author      : ShiGuang 

// Version     : 

// Copyright   : [email protected] 

// Description : Hello World in C++, Ansi-style 

//============================================================================ 

 

#include <iostream> 

#include<string> 

 

using namespace std; 

class Student 

    int semesHours; 

    float gpa; 

public: 

    Student(int i) 

    { 

        cout << "constructing student.\n"; 

        semesHours = i; 

        gpa = 3.5; 

    } 

    ~Student() 

    { 

        cout << "~Student\n"; 

    } 

}; 

 

class Teacher 

    string name; 

public: 

    Teacher(string p) 

    { 

        name = p; 

        cout << "constructing teacher.\n"; 

    } 

    ~Teacher() 

    { 

        cout << "~Teacher\n"; 

    } 

}; 

 

class TutorPair 

public: 

    TutorPair(int i, int j, string p) : 

        teacher(p), student(j) 

    { 

        cout << "constructing tutorpair.\n"; 

        noMeetings = i; 

    } 

    ~TutorPair() 

    { 

        cout << "~TutorPair\n"; 

    } 

protected: 

    Student student; 

    Teacher teacher; 

    int noMeetings; 

}; 

 

int main(int argc, char **argv) 

    TutorPair tp(5, 20, "Jane"); 

    cout << "back in main.\n"; 

    return 0; 

注意:程序裡面的賦值方式,以及構造函數析構函數的調用次序。

 

constructing student. 

constructing teacher. 

constructing tutorpair. 

back in main. 

~TutorPair 

~Teacher 

~Student 

另外:構造函數初始化常數據成員和引用成員。

 

 

//============================================================================ 

// Name        : main.cpp 

// Author      : ShiGuang 

// Version     : 

// Copyright   : [email protected] 

// Description : Hello World in C++, Ansi-style 

//============================================================================ 

 

#include <iostream> 

#include <string> 

 

using namespace std; 

 

class Student 

public: 

    Student(int s, int &k) : 

        i(s), j(k) 

    { 

    } //不可以直接賦值 

    void p() 

    { 

        cout << i << endl; 

        cout << j << endl; 

    } 

protected: 

    const int i; 

    int &j; 

}; 

 

int main(int argc, char **argv) 

    int c = 123; 

    Student s(9818, c); 

    s.p(); 

 

    return 0; 

 

9818 

123   

 

摘自 sg131971的學習筆記

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved