C++构造函数初始化列表
生活随笔
收集整理的這篇文章主要介紹了
C++构造函数初始化列表
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
第一種寫法
#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<<",的成績(jī)是"<<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<<",成績(jī)是"<<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<<",的成績(jī)是"<<m_score<<endl; }int main() {Student stu("小明",15,93);stu.show();Student *pstu=new Student("李華",16,96);pstu->show();return 0;}總結(jié)
以上是生活随笔為你收集整理的C++构造函数初始化列表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C++ new和delete(C++动态
- 下一篇: C++成员对象和封闭类