C++构造函数初始化列表

第一种写法
#include <iostream>
using namespace std;

class Student{


        private:
                char *m_name;
                int   m_age;
                float m_score;

        public:
                Student(char *name,int age ,float score);
                void show();

};

//采用初始化列表

Student::Student(char *name,int age ,float score):m_name(name),m_age(age),m_score(score){}

void Student::show(){

    cout<<m_name<<"的年龄是"<<m_age<<",的成绩是"<<m_score<<endl;
}

int main()
{
        Student stu("小明",15,93);
        stu.show();
        Student *pstu=new Student("李华",16,96);

        pstu->show();
        return 0;

}


第二种写法
#include <iostream>
#include <string>

using namespace std;


class Student{
private:
   string m_name;
    int m_age;
    float m_score;
public:
    Student(string name, int age, float score);
    void show();
};
//采用初始化列表

Student::Student(string name, int age, float score){
    //;
    m_name=name;
    m_age=age;
    m_score=score;

}

void Student::show(){
    cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
}
int main(){
    Student stu("小明", 15, 92.5);
    stu.show();
    Student *pstu = new Student("李华", 16, 96);
    pstu -> show();
    return 0;
}
第三种写法
#include <iostream>
using namespace std;

class Student{


private:
    char *m_name;
    int   m_age;
    float m_score;

public:
    Student(char *name,int age ,float score);
    void show();

};

//采用初始化列表

Student::Student(char *name,int age ,float score):m_name(name){

    m_score=score;
    m_age=age;

}

void Student::show(){

    cout<<m_name<<"的年龄是"<<m_age<<",的成绩是"<<m_score<<endl;
}

int main()
{
    Student stu("小明",15,93);
    stu.show();
    Student *pstu=new Student("李华",16,96);

    pstu->show();
    return 0;

}

posted @ 2022-08-19 22:48  luoganttcc  阅读(4)  评论(0)    收藏  举报