C++学习复习笔记05 – 构造函数重载时的写法
在C++类中进行构造函数重载时,有几种不同的简洁的写法。
下面先演示可读性最好的也是初学时常用的写法一:
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string name;
int age;
public:
Person()
{
cout << "Person()" << endl;
}
// 构造函数一经重写,系统默认的无参数的将不复存在,若要使用得写出来
Person(string name, int age)
{
this->name = name;
this->age = age;
cout << "Person(string name, int age)" << endl;
}
};
int main()
{
Person wuxie;
Person xiaoge("张起灵", 22);
return 0;
}
写法2
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string name;
int age;
public:
Person()
{
cout << "Person()" << endl;
}
// 构造函数一经重写,系统默认的无参数的将不复存在,若要使用得写出来
Person(string name, int age): name(name), age(age)
{
cout << "Person(string name, int age)" << endl;
}
};
int main()
{
Person wuxie;
Person xiaoge("张起灵", 22);
return 0;
}
写法3
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string name;
int age;
public:
// 增加参数的默认值后,默认的Person()不能再写了,
// 因为有默认值的参数包含了Person()存在的情况,再写出来就会出错
Person(string name="吴邪", int age=20): name(name), age(age)
{
cout << "Person(string name, int age)" << endl;
}
};
int main()
{
Person wuxie;
Person xiaoge("张起灵", 22);
return 0;
}
除非注明,戊辰人博客文章均为原创,转载请以链接形式标明本文地址