#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){ //TODO: } void Student::show(){ cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl; } int main(){ Student stu("小明", 15, 92.5f); stu.show(); Student *pstu = new Student("李华", 16, 96); pstu -> show(); return 0; }运行结果:
:
,后面紧跟m_name(name), m_age(age), m_score(score)
语句,这个语句的意思相当于函数体内部的m_name = name; m_age = age; m_score = score;
语句,也是赋值的意思。Student::Student(char *name, int age, float score): m_name(name){ m_age = age; m_score = score; }注意,成员变量的初始化顺序与初始化列表中列出的变量的顺序无关,它只与成员变量在类中声明的顺序有关。请看代码:
#include <iostream> using namespace std; class Demo{ private: int m_a; int m_b; public: Demo(int b); void show(); }; Demo::Demo(int b): m_b(b), m_a(m_b){ } void Demo::show(){ cout<<m_a<<", "<<m_b<<endl; } int main(){ Demo obj(100); obj.show(); return 0; }运行结果:
Demo::Demo(int b): m_b(b), m_a(m_b){ m_a = m_b; m_b = b; }给 m_a 赋值时,m_b 还未被初始化,它的值是不确定的,所以输出的 m_a 的值是一个奇怪的数字;给 m_a 赋值完成后才给 m_b 赋值,此时 m_b 的值才是 100。
class VLA{ private: const int m_len; int *m_arr; public: VLA(int len); }; //必须使用初始化列表来初始化 m_len VLA::VLA(int len): m_len(len){ m_arr = new int[len]; }VLA 类包含了两个成员变量,m_len 和 m_arr 指针,需要注意的是 m_len 加了 const 修饰,只能使用初始化列表的方式赋值,如果写作下面的形式是错误的:
class VLA{ private: const int m_len; int *m_arr; public: VLA(int len); }; VLA::VLA(int len){ m_len = len; m_arr = new int[len]; }
本文链接:http://task.lmcjl.com/news/8449.html