1、构造析构拷贝函数都没有返回值
2、构造函数可以重载
3、析构函数没有形参
4、手动调用析构函数后程序还会再次调用,确保调用两次不会影响程序
5、拷贝构造函数的初始化形式
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
class Test
{
private:
int m_x;
int m_y;
public:
Test()
{
m_x = 0;
m_y = 0;
}
Test(int x, int y)
{
m_x = x;
m_y = y;
}
void printT()
{
std::cout << "x = " << m_x << ", y = " << m_y << std::endl;
}
Test(const Test &T) // 拷贝构造函数
{
std::cout << "Test(const Test &T)..." << std::endl;
m_x = T.m_x;
m_y = T.m_y;
}
void operator = (const Test &T) //=运算符重载
{
std::cout << "operator = (const Test &T)..." << std::endl;
m_x = T.m_x;
m_y = T.m_y;
}
};
int main()
{
Test t1(100, 200);
Test t2(t1); //调用拷贝构造函数
t2.printT();
Test t3 = t1; //调用拷贝构造函数
Test t4;
t4 = t1; //调用=运算符重载
return 0;
}
拷贝构造函数应用场景
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
class Test
{
private:
int m_x;
int m_y;
public:
Test()
{
std::cout << "Test()..." << std::endl;
m_x = 0;
m_y = 0;
}
Test(int x, int y)
{
std::cout << "Test(int x, int y)..." << std::endl;
m_x = x;
m_y = y;
}
Test(const Test &another)
{
std::cout << "Test(const Test &another)..." << std::endl;
m_x = another.m_x;
m_y = another.m_y;
}
void operator = (const Test &another)
{
std::cout << "void operator = (const Test &another)..." << std::endl;
m_x = another.m_x;
m_y = another.m_y;
}
void printT()
{
std::cout << "m_x = " << m_x << ", m_y = " << m_y << std::endl;
}
~Test()
{
std::cout << "~Test()..." << std::endl;
}
};
//场景1
void test1()
{
Test t1(10, 20);
Test t2(t1);
}
//场景2
void test2()
{
Test t1(10, 20);
Test t2;
t2 = t1;
}
void fun(Test t) // Test t = t1; //Test t 的拷贝构造函数
{
std::cout << "func begin..." << std::endl;
t.printT();
std::cout << "func end..." << std::endl;
}
//场景3
void test3()
{
std::cout << "test3 begin..." << std::endl;
Test t1(10, 20);
fun(t1);
std::cout << "test3 end..." << std::endl;
}
Test fun2()
{
std::cout << "fun2 begin..." << std::endl;
Test temp(10, 20);
temp.printT();
std::cout << "fun2 end..." << std::endl;
return temp; // 匿名的对象 = temp 匿名对象.拷贝构造(temp)
}
//场景4
void test4()
{
std::cout << "test4 begin..." << std::endl;
fun2(); // 返回一个匿名对象,如果函数外部没有变量去接收它
// 这个匿名对象将不会再被使用 (找不到)
// 编译会直接将这个匿名对象回收
// 而不是等待整个函数执行完毕再回收
std::cout << "test4 end..." << std::endl;
}
void test5()
{
std::cout << "test5 begin..." << std::endl;
Test t1 = fun2(); // 并不会触发t1拷贝,而是将匿名对象转正 t1
// 这个匿名对象起了名字脚t1
std::cout << "test5 end..." << std::endl;
}
//场景6
void test6()
{
std::cout << "test6 begin..." << std::endl;
Test t1; // t1已经被初始化
t1 = fun2(); // =操作符
t1.printT();
std::cout << "test6 end..." << std::endl;
}
int main()
{
//test1();
//test2();
//test3();
//test4();
//test5();
test6();
return 0;
}