zoukankan      html  css  js  c++  java
  • c++使用初始化列表来初始化字段

    #include<iostream>
    using namespace std;
    
    class Student1
    {
    private:
    	int _a;
        int _b;
    
    public:
        void
        fprint()
        {
            cout << " a = " << _a << " " << "b = " << _b << endl;
        }
    
        //Student1(int i):b(i),a(b){ }    //异常顺序:发现a的值为0  b的值为2  说明初始化仅仅对b有效果,对a没有起到初始化作用
        
    	Student1(int a, int b): _a(a), _b(b) 
    	{ 
    		cout << "constructor" << endl;
    	} //正常顺序:发现a = b = 2 说明两个变量都是初始化了的
    
        Student1()                         // 无参构造函数
        {
            cout << "默认构造函数Student1" << endl ;
        }
    
        Student1(const Student1 &t1) //拷贝构造函数
        {
            cout << "拷贝构造函数Student1" << endl ;
            this->_a = t1._a;
    		this->_b = t1._b;
        }
    
        Student1 &
        operator = (const Student1 &t1) // 赋值运算符
        {
            cout << "赋值函数Student1" << endl ;
            this->_a = t1._a ;
    		this->_b = t1._b ;
            return *this;
        }
    
    };
    
    class Teacher
    {
    public:
        Student1 test;	//类中包含类
        Teacher(Student1 &t1)
        {
            test  = t1 ;
        }
    };
    
    int main(void)
    {
        Student1 A(2,4);      //进入默认构造函数
        Teacher B(A);        //进入拷贝构造函数
        A.fprint();           //输出前面初始化的结果
    	B.test.fprint();
    }
    

      

  • 相关阅读:
    ubuntu在图形界面下打开一个终端
    [置顶] 屠夫与大夫
    service bound(一)
    Android Interface Definition Language (AIDL)
    service bound(二)
    移动应用开发原则
    Service bound(三)
    Linux 安装SSH服务
    JDK中设计模式
    Bad Hair Day【单调栈】
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/11182200.html
Copyright © 2011-2022 走看看