拷贝构造函数
爆炸性先验结论
c++调用拷贝构造函数时,不会调用类的构造函数。(拷贝构造函数也是构造函数的一种,每次只调用一个构造函数)。
问题描述
很多人对c++的拷贝构造函数和赋值=运算区分不清楚。如下面的代码所示:
int main()
{
std::cout << " test1 : \n";
Point pt1; //test1
std::cout << " test2 : \n";
Point pt2 = pt1;//test2
std::cout << " test3 : \n";
Point pt3;//test3
pt3 = pt1;//test3
std::cout << " test4 : \n";
Point pt4(pt1);//test4
std::cout << "\n\n\n";
return 0;
}
test2、test3、test4的区别是什么?下面通过一个实例进行认识。
Point源码
class Point
{
public:
Point();
Point(int x, int y);
Point(const Point& pt);
void operator = (const Point &pt);
public:
int x_;
int y_;
};
Point::Point()//构造函数
:x_(0)
,y_(0)
{
std::cout << "Point()\n";
}
Point::Point(int x, int y)//构造函数
:x_(x)
,y_(y)
{
std::cout << "Point(int x, int y)\n";
}
Point::Point(const Point& pt)//拷贝构造函数
{
x_ = pt.x_;
y_ = pt.y_;
std::cout << "Point(const Point& pt) \n";
}
void Point::operator = (const Point &pt)//赋值运算
{
x_ = pt.x_;
y_ = pt.y_;
std::cout << "operator = (const Point &pt) \n";
}
实例测试
程序源码
程序源码其实组合上面两部分就是了,这里还是啰嗦下给出完整的代码。
#include <iostream>
class Point
{
public:
Point();
Point(int x, int y);
Point(const Point& pt);
void operator = (const Point &pt);
public:
int x_;
int y_;
};
Point::Point()
:x_(0)
,y_(0)
{
std::cout << "Point()\n";
}
Point::Point(int x, int y)
:x_(x)
,y_(y)
{
std::cout << "Point(int x, int y)\n";
}
Point::Point(const Point& pt)
{
x_ = pt.x_;
y_ = pt.y_;
std::cout << "Point(const Point& pt) \n";
}
void Point::operator = (const Point &pt)
{
x_ = pt.x_;
y_ = pt.y_;
std::cout << "operator = (const Point &pt) \n";
}
int main()
{
std::cout << " test1 : \n";
Point pt1;//test1
std::cout << " test2 : \n";
Point pt2 = pt1;//test2
std::cout << " test3 : \n";
Point pt3;//test3
pt3 = pt1;//test3
std::cout << " test4 : \n";
Point pt4(pt1);//test4
std::cout << "\n\n\n";
return 0;
}
运行结果
结论
(1)test2实例中,只调用了拷贝构造函数,需要特别注意的是,pt2并没有调用构造函数Point()。
(2)test4也一样,只调用了拷贝构造函数,pt4并没有调用构造函数Point()。
(3)test3 首先对pt3调用了Point()构造函数,然后调用了赋值表达式。
(4)像test2与test4那样形式的是调用拷贝构造函数
(5)test3那种,先定义对象,再调用=的才是赋值操作。
C++拷贝构造与赋值区别

本文详细解析了C++中拷贝构造函数与赋值运算符的区别,通过具体示例阐述了两者在对象初始化及赋值过程中的不同行为。
1079

被折叠的 条评论
为什么被折叠?



