WHCSRL 技术网

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;

}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
第二种写法
#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
第三种写法
#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;

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
推荐阅读