C++初始化列表实现构造方法

it2023-02-01  52

C++带参构造函数支持常规使用和初始化列表形式。

初始化列表语法:

构造函数(): 属性1(值1), 属性2(值2),,属性n (值n){}

程序源码:

#include <iostream> #include <string> using namespace std; class Teacher { public: //常规 带参构造函数写法 Teacher(string name, string course) { this->name = name; this->course = course; cout << "带参construction" << endl; } //声明带参构造函数 Teacher(string name, string course, int num); public: string name; string course; int num; }; //初始化列表来创建构造方法 Teacher::Teacher(string name, string course, int num): name(name), course(course), num(num) { cout << "()-() construct" << endl; } int main() { Teacher t2("语文老师", "Chinese"); cout << t2.name << ", course=" << t2.course << endl; Teacher t3("体育老师", "1000"); cout << t3.name << ", num" << t3.num << endl; return 0; }

 

最新回复(0)