拷贝构造函数,显式与隐式拷贝构造函数用法如下:
#include "pointer.hpp"
#include <iostream>
using namespace std;
int main(int argc, const char *argv[])
{
pointer p1(5,6);
cout << "x:" << p1.getx() << " y:" << p1.gety() <<endl;
cout << "-------------------" << endl;
pointer p2(p1);//显示调用拷贝构造函数
pointer p3 = p1;//隐士调用拷贝构造函数
cout << "-------------------" << endl;
pointer p4;
p4 = p1;//没调用拷贝构造函数
p4.show(p1);
cout << "---------------" << endl;
pointer p5 = test();
//结果会输出一个默认构造函数输出和test,不会调用拷贝构造函数
//通过编译选项可以把p5的地址传到test的p当中去
//如果运行时候g++ xxx.cpp -fno-elide-constructors
//强制调用拷贝构造函数
//test不仅可以输出之前的结果还会输出两个拷贝构造函数的输出
//return p的时候会产生一个临时对象,编译器经过优化不会
//显示出来,出来加上面的编译选项,另外p5会接住也会输出拷贝函数
pointer &p6 = p5;//不会调用拷贝构造函数i,只是多了个指向,并不是真正意义
//的复制
pointer *p7 = &p5;//也不会调用拷贝构造函数
return 0;
}
#include "pointer.hpp"
#include <iostream>
using namespace std;
pointer::pointer()
{
cout << "调用默认构造函数" << endl;
x = 10;
y = 10;
}
pointer::pointer(int _x,int _y):x(_x),y(_y)
{
cout << "调用构造函数" << endl;
}
pointer::pointer(const pointer &other) : x(other.x),y(other.y)
{
cout << "调用拷贝构造函数 " << endl;
}
int pointer::getx()
{
return x;
}
int pointer::gety()
{
return y;
}
void pointer::setxy(int _x,int _y)
{
x = _x;
y = _y;
}
void pointer::show(pointer other)
{
cout << "show" << other.x << " " << other.y <<endl;
}
pointer test()
{
pointer p;
cout << "test" << endl;
return p;//这里编译器会优化,不加编译选项强制输出拷贝构造函数的话结果只会输出test
}
#ifndef POINTER_HPP
#define POINTER_HPP
#include <iostream>
class pointer
{
public:
pointer();
pointer(int _x,int _y);
pointer(const pointer &other);//拷贝构造函数声明
int getx();
int gety();
void setxy(int _x,int _y);
void show(pointer other);
private:
int x;
int y;
};
pointer test();
#endif