C++ | 使用成员初始化列表对成员数据初始化

时间:2022-05-17 05:49:23

简介:

  在c++的声明类中,初始化数据成员除了在构造函数中用赋值语句进行外还提供一种 成员初始化列表 实现对数据成员的初始化。这种写法方便简练,在需要初始化的数据成员比较多时能够显示其优越性。

使用方法:

  

#include<iostream>
using namespace std;
class point{
    public :
        point(){
        }
        point(double x,double y):x_(x),y_(y){
        }
        print(){ 
            cout<<"x:"<<this->x_<<" y:"<<this->y_<<endl; 
        } 
    private:
        double x_;
        double y_;
};
int main(){
    point p(2.3,4.5);
    p.print();
}

 

必须使用的三种情景:

  https://blog.csdn.net/u011857683/article/details/79720782

C++ | 使用成员初始化列表对成员数据初始化