#include<iostream>
using namespace std;
class A
{
public:
explicit A() // explicit修饰构造函数,为了防止隐式类型转换,规定必须要显示调用
{
cout<<"construct A"<<endl;
};
A(const A &a)// 拷贝构造函数,另外系统提供一个默认的拷贝构造函数,使用位拷贝,存在指针成员变量时,一定要重写该函数,防止内存泄露。
{
cout<<"copy construct"<<endl;
{
cout<<"assign construct"<<endl;
return *this;
};
{
cout<<"test function"<<endl;
return 0;
}
int main()
{
A b(a);//拷贝构造函数
b = a;//赋值运算
test(a);
return 0;
}
using namespace std;
class A
{
public:
explicit A() // explicit修饰构造函数,为了防止隐式类型转换,规定必须要显示调用
{
cout<<"construct A"<<endl;
};
A(const A &a)// 拷贝构造函数,另外系统提供一个默认的拷贝构造函数,使用位拷贝,存在指针成员变量时,一定要重写该函数,防止内存泄露。
{
cout<<"copy construct"<<endl;
};
//赋值操作符重载,一般有拷贝构造函数都会伴随有该函数
A& operator=(const A &a){
cout<<"assign construct"<<endl;
return *this;
};
};
//在函数使用值传递时,和返回对象时都会调用拷贝构造函数,为了提高性能,一般最好使用引用
int test(A a){
cout<<"test function"<<endl;
return 0;
}
int main()
{
A a;//默认构造函数
//拷贝构造函数,这里应该是有个隐式转换,当变量未定义时,调用的是拷贝构造函数而不是赋值运算符的重载函数
A b(a);//拷贝构造函数
b = a;//赋值运算
test(a);
return 0;
}