一、基本概念:
1、用一个类的对象初始化该类的另一个对象被称为缺省按成员初始化,在概念上,一个类的对象向该类的另一个对象作拷贝是通过调用拷贝构造函数实现的,而拷贝构造函数由编译器提供,并依次拷贝每个非静态数据成员来实现。类的设计者也可以通过提供特殊的拷贝构造函数来改变缺省的行为,如果定义了拷贝构造函数,则在用一个类的对象初始化该类另一个对象时它就会被调用。
2、本质上还是一个构造函数,只是函数的参数,是一个本类类型的对象
二、第一种用法 A a2 = a1;
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "我是构造函数,自动被调用了" << endl;
}
A(const A &obj)
{
cout << "我也是构造函数,我是通过另一个对象来初始化我自己" << endl;
}
~A()
{
cout << "我是析构函数,自动被调用了" << endl;
}
private:
int a;
};
int main()
{
A a1;
A a2 = a1;
system("pause");
return 0;
}
运行结果:
注意:A a2 = a1;与a2=a1;是不同的,后者是用a1来=号给a2,是编译器给我们提供的浅拷贝。
三、第二种用法 A a2(a1);
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "我是构造函数,自动被调用了" << endl;
}
A(int _a)
{
a = _a;
}
A(const A &obj)
{
a = obj.a;
cout << "我也是构造函数,我是通过另一个对象来初始化我自己" << endl;
}
~A()
{
cout << "我是析构函数,自动被调用了" << endl;
}
void getA()
{
cout << "a=" << a << endl;
}
private:
int a;
};
int main()
{
A a1(10);
A a2(a1);
a2.getA();
system("pause");
return 0;
}
运行结果:
四、第三种用法,当函数的形参是对象时,会调用拷贝构造函数来进行形参的初始化
#include "iostream"
using namespace std;
class Point
{
public:
Point(int xx = 0, int yy = 0)
{
X = xx; Y = yy; cout << "Constructor Object.\n";
}
Point(const Point & p) //复制构造函数
{
X = p.X; Y = p.Y; cout << "Copy_constructor called." << endl;
}
~Point()
{
cout << X << "," << Y << " Object destroyed." << endl;
}
int GetX() { return X; } int GetY() { return Y; }
private: int X, Y;
};
void f(Point p)
{
cout << "Funtion:" << p.GetX() << "," << p.GetY() << endl;
}
void main()
{
Point A(1, 2);
f(A);
system("pause");
}
运行结果:
五、第四种用法:函数返回类类型时,通过复制构造函数建立临时对象
#include "iostream"
using namespace std;
class Point
{
public:
Point(int xx = 0, int yy = 0)
{
X = xx; Y = yy; cout << "Constructor Object.\n";
}
Point(const Point & p) //复制构造函数
{
X = p.X; Y = p.Y; cout << "Copy_constructor called." << endl;
}
~Point()
{
cout << X << "," << Y << " Object destroyed." << endl;
}
int GetX() { return X; } int GetY() { return Y; }
private: int X, Y;
};
Point g()
{
Point A(1, 2);
return A;//把局部对象A复制到匿名对象
}
void main()
{
Point B;
B = g();
system("pause");
}
运行结果:
本文详细介绍了拷贝构造函数的概念及四种使用场景:赋值初始化、括号传递对象、函数参数传递及函数返回对象。通过具体示例展示了拷贝构造函数在C++中的工作原理。

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



