?隐式构造函数
//?C++?中存在隐式构造的现象:某些情况下,会隐式调用单参数的构造函数
// 隐式构造函数
// C++ 中存在隐式构造的现象:某些情况下,会隐式调用单参数的构造函数
#include <iostream>
#include <cstring>
using namespace std;
class Person
{
private:
int m_age;
public:
Person(/* args */)
{
cout << "Persion() -" << this << endl;
}
Person(int age) :m_age(age)
{
cout << "Persion(int) -" << this << endl;
}
~ Person(){
cout << "~ Persion() -" << this << endl;
}
void display() {
cout << "display() gae is " << m_age <<endl;
}
};
void test1(Person Person){}
Person test2(){
return 30;
}
int main(){
cout << "test 1:"<< endl;
Person p1 = 20;
cout << "test 2:"<< endl;
Person p2(20);
cout << "test 3:"<< endl;
test1(30);
cout << "test 4:"<< endl;
test2();
cout << "test 5:"<< endl;
getchar();
return 0;
}
//结果
test 1:
Persion(int) -0x61fe04
test 2:
Persion(int) -0x61fe00
test 3:
Persion(int) -0x61fe08
~ Persion() -0x61fe08
test 4:
Persion(int) -0x61fe0c
~ Persion() -0x61fe0c
test 5:
~ Persion() -0x61fe00
~ Persion() -0x61fe04
避免隐式构造:添加explicit关键字
class Person
{
private:
int m_age;
public:
Person()
{
cout << "Persion() -" << this << endl;
}
explicit Person(int age) :m_age(age)
{
cout << "Persion(int) -" << this << endl;
}
~ Person(){
cout << "~ Persion() -" << this << endl;
}
void display() {
cout << "display() gae is " << m_age <<endl;
}
};
void test1(Person Person){}
Person test2(){
return Person(70);
}
int main(){
cout << "test 1:"<< endl;
Person p1 = Person(40);
cout << "test 2:"<< endl;
Person p2(50);
cout << "test 3:"<< endl;
test1(Person(60));
cout << "test 4:"<< endl;
test2();
cout << "test 5:"<< endl;
getchar();
return 0;
}
// 结果
test 1:
Persion(int) -0x61fe04
test 2:
Persion(int) -0x61fe00
test 3:
Persion(int) -0x61fe08
~ Persion() -0x61fe08
test 4:
Persion(int) -0x61fe0c
~ Persion() -0x61fe0c
test 5:
~ Persion() -0x61fe00
~ Persion() -0x61fe04
|