C++自动提供了五个特殊成员函数(如果未自己定义)
- 默认构造函数
- 默认析构函数
- 复制构造函数
- 赋值运算符重载
- 地址运算符重载
复制构造函数与赋值运算符重载的应用情况:
class A {
...
}
A a = {...};
//调用复制构造函数
A b(a);
A c = a;
//调用赋值运算符
A d;
d = a;
在类成员变量中含有指针的情况下,必须自己提供类的复制构造函数、赋值运算符,否则,赋值/赋值之后,两个对象的指针成员将指向同一个地址。
下面给出了一个例子
Tclass.h
#ifndef TCLASS_H_
#define TCLASS_H_
#include <iostream>
using std::cout;
using std::endl;
class Tclass
{
private:
char ch;
public:
Tclass();
Tclass(char c);
Tclass(const Tclass & a);
Tclass & operator=(const Tclass & a);
static void func();
~Tclass();
};
//常规函数实现需要放到Tclass.cpp中
//这里为了防止某些IDE链接器问题,直接放在了.h文件中
//下面三个构造函数实际都是 a.Tclass(...)
//所以可以无需返回值,相当于直接修改对象a的私有成员
void Tclass::func(){
cout << "func" << endl;
}
Tclass::Tclass()
{
ch = '0';
cout << "Default func: " << ch << endl;
}
Tclass::Tclass(char c){
ch = c;
cout << "Func: " << ch << endl;
}
//复制构造函数
Tclass::Tclass(const Tclass & a){
ch = a.ch;
cout << "Copy func: " << ch << endl;
}
//注意如果定义成 const成员函数,将不能修改成员
//所以需要根据运算符的性质,决定是否需要使用const!!!
// a = b * c b.op*(c) 可以定义并返回一个临时变量的引用,所以可以用const
// a = b a.op=(b) 对象a的op=()函数需要修改a的成员,所以坚决不能定义成const
//运算符重载
Tclass &
Tclass::operator=(const Tclass & a) {
if (this == &a)
return *this;
ch = a.ch;
cout << "Overload = func: " << ch << endl;
}
Tclass::~Tclass()
{
cout << "unfunc: " << ch << endl;
}
#endif
main.cpp
#include <iostream>
#include "Tclass.h"
void funca();
Tclass & funcb(const Tclass & a);
int main(){
funca();
return 0;
}
void funca(){
Tclass a{'a'};
Tclass b('b');
Tclass c = {'c'};
Tclass d = a, e;
e = b;
Tclass f(c);
}
可以执行上面这个例子,看一下输出,具体调用的是构造函数还是其余的函数
运行结果如下:
Func: a
Func: b
Func: c
Copy func: a
Default func: 0
Overload = func: b
Copy func: c
unfunc: c
unfunc: b
unfunc: a
unfunc: c
unfunc: b
unfunc: a