c++类成员初始化
1. 构造函数初始化成员
#include <iostream>
using namespace std;
class People
{
public:
People() :name("tom"), age(20), func([](int a, int b)-> int { return a + b; })
{
}
char name[32];
int age;
int(*func)(int, int);
};
//构造函数初始化成员
//使用初始化表初始化
int main(int argc, char *argv[])
{
People people;
cout << people.name << endl;
cout << people.age << endl;
cout << people.func(100, 200) << endl;
cin.get();
return 0;
}
2.类成员默认初始化
#include <iostream>
using namespace std;
class People
{
public:
//对成员默认初始化,有2种方式
//1. 成员=赋值
//2. 成员{赋值}
char name[32] = "tom"; //第一种
int age{ 5 }; //第二种
int(*func)(int, int) = [](int a, int b) {return a + b; };
};
//对类成员默认初始化
int main(int argc, char *argv[])
{
People people;
cout << "name:" << people.name << endl;
cout << "age:" << people.age << endl;
cout << "func:" << people.func(100, 200) << endl;
cin.get();
return 0;
}
秋风
2018-03-18