构造函数默认参数
#include <iostream>
class C_Example{
public:
int m_number;
C_Example(int number = 6){
m_number = number;
}
};
int main(){
//报错:C_Example example();
C_Example example;
std::cout << example.m_number << std::endl;
}
但如果实例化为匿名对象,则依然需要()
#include <iostream>
class C_Example{
public:
int m_number;
C_Example(int number = 6){
m_number = number;
} //含有构造函数默认参数
void PrintNumber(){
std::cout << m_number << std::out;
}
};
int main(){
C_Example().example()
}
//Output >> 6
构造函数后的冒号
构造函数后加冒号是初始化表达式。
-
初始化const成员或引用成员(仅该方法)
class C_Example{ public: const int m_numberA; int &m_numberB; C_Example(); }; C_Example::C_Example(int numberA, int numberB):m_numberA(numberA), numberB(numberB){ ... };
-
想通过对构造函数传参直接赋值成员(一般不这么用)
#include <iostream> class C_Example{ public: int m_number; C_Example(int number):m_number(number){} }; int main(){ C_Example example(6); std::cout << example.m_number << std::endl; } //Output >> 6
-
当调用派生类的构造函数时,想直接赋值(初始化)基类的成员
#include <string> using namespace std; class Parent{ protected: string m_firstName; string m_lastName; Parent(string firstName, string lastName){ m_firstName = firstName; m_lastName = lastName; } }; class Son: public Parent{ public: string m_sonLastName; Son(string parentFirstName, string parentLastName, string sonLastName): Parent(parentFirstName, parentLastName), m_sonLastName(sonLastName){}; //初始化表达式中Parent()就是调用基类的构造函数 /*派生类不能直接初始化基类的成员,会出现成员不存在的错误 * 报错写法: Son(string parentFirstName, string parentLastName, string sonLastName): m_firstName(parentFirstName)... */ };