类中默认的六个方法:
- 构造函数
- 拷贝构造函数
- 析构函数
- 赋值构造函数
- 普通对象的取地址函数
- 常对象的取地址函数
代码如下:
#include<iostream>
using namespace std;
class Test
{
public:
Test(int data = 0):m_data(data) //构造函数
{
cout << "Create Test." << this << endl;
}
Test(const Test &t) //拷贝构造函数
{
m_data = t.m_data;
cout << "Copy create Test." << this << endl;
}
Test& operator=(const Test &t) //赋值构造函数
{
cout << "Assign:" << this << "=" << &t << endl;
if(this != &t)
{
m_data = t.m_data;
}
return *this;
}
~Test() //析构函数
{
cout << "Free Test." << this << endl;
}
public:
Test* operator&() //普通对象的取地址函数
{
cout << "Object get adress." << endl;
return this;
}
const Test* operator&()const //常对象的取地址函数
{
cout << "const object get adress." << endl;
return this;
}
private:
int m_data;
};
int main()
{
Test t; //调用构造函数
Test t1; //调用构造函数
t1 = t; //调用赋值构造函数和常对象的取地址函数
Test t2 = t; //调用拷贝构造函数和常对象的取地址函数
Test *p = &t;//调用普通对象的取地址函数
const Test t3;//调用构造函数
const Test *p1 = NULL;
p1 = &t3; //调用常对象的取地址函数
return 0;
}
运行结果如下:
下面单击即可跳转~