头文件Test.h
#pragma once
class Test
{
public:
Test();
Test(int num);
~Test();
void Display();
Test& operator=(const Test& other);
private:
int num_;
};
实现文件Test.cpp
#include "Test.h"
#include <iostream>
using namespace std;
Test::Test()
{
num_ = 0;
cout << "Initnitialing Default" << endl;
}
Test::Test(int num)
{
num_ = num;
cout << "Initnitialing " << num_ << endl;
}
Test::~Test()
{
cout << "Destroy " << num_ << endl;
}
void Test::Display()
{
cout << "num = " << num_ << endl;
}
Test& Test::operator=(const Test& other)
{
cout << "Test::operator=" << endl;
// 重载==后可以写成if (*this == other)
if (this == &other)
return *this;
num_ = other.num_;
return *this;
}
转换构造函数
1.转换构造函数是有单个参数的构造函数。带一个参数的构造函数可以分为普通构造函数(初始化)和转换构造函数(初始化、类型转化)
2.将其他类型转换为类类型
3.类的构造函数只有一个参数是非常危险的,因为编译器可以使用这种构造函数把参数的类型隐式转换为类类型。
#include <iostream>
#include "Test.h"
using namespace std;
int main()
{
Test t(10); // 调用带一个参数的构造函数,充当的是普通构造函数的功能。
t = 20; // 将20这个整数赋值给t对象。
// 1.这时将会调用转换构造函数将20这个整数转换为类类型(生成一个临时对象)
// 2.将临时对象赋值给t(调用=运算符)
t.Display();
return 0;
}
赋值与初始化区别
1.在初始化语句中的等号不是运算符。编译器对这种表示方法有特殊的解释。
2.赋值
3.Test& Test::operator=(const Test& other);
#include <iostream>
#include "Test.h"
using namespace std;
int main()
{
Test t(10); // 调用带一个参数的构造函数,充当的是普通构造函数的功能。
Test t1 = 20; // 等价Test t(20);
return 0;
}
#include <iostream>
#include "Test.h"
using namespace std;
int main()
{
Test t(10); // 调用带一个参数的构造函数,充当的是普通构造函数的功能。
Test t1 = 20; // 等价Test t(20);这里的=不是运算符,表示初始化。
t = 30; // 赋值操作
Test t2;
t = t2; // 赋值操作 t.operator=(t2);
return 0;
}
explicit
1.只提供给类的构造函数使用的关键字
2.编译器不会把声明为explicit的构造函数用于隐式转换,它只能在程序代码中显示创建对象。
编译不会通过。