在C++类中同样的默认成员函数一共有六个,即使用户不定义,编译器也可以给出。分别为:
1、构造函数;
2、析构函数;
3、拷贝构造函数;
4、赋值运算;
5、取地址运算;
6、const取地址运算;
我们一下述程序为例验证下上面说法:
#include <iostream>
using namespace std;
class complex
{
public:
complex() //构造函数
{
cout << "complex()!!\n";
}
~complex() //析构函数
{
cout << "~complex()!!" << endl;
}
complex(const complex &c) //拷贝构造函数
{
m_real = c.m_real;
m_image = c.m_image;
cout << "complex(const comple &c)!!" << endl;
}
complex& operator=(const complex &c) //赋值运算
{
if(this != &c){
m_real = c.m_real;
m_image = c.m_image;
}
cout << "complex operator=(const complex &c)!!" << endl;
return *this;
}
complex* operator&(const complex &x) //取地址运算
{
cout << "complex& operator=(const complex &x)!!" << endl;
return this;
}
const complex* operator=(const complex &c)const //const取地址运算
{
cout << "const complex& operator=(const complex &c)const!!" << endl;
return this;
}
private:
int m_real;
int m_image;
};
int main()
{
complex c1; //构造函数
complex c2 = c1; //拷贝构造函数
complex c3; //构造函数
c3 = c1; //赋值运算
complex *pa = &c2; //取地址运算
const complex *pb = &c2; //const取地址运算
return 0;
}
*运行结果:*
我们可以看到每次都调用了相应的函数,下面我们看下如果不定义这些程序会不会成功运行吧!
#include <iostream>
using namespace std;
class complex
{
public:
private:
int m_real;
int m_image;
};
int main()
{
complex c1; //构造函数
complex c2 = c1; //拷贝构造函数
complex c3; //构造函数
c3 = c1; //赋值运算
complex *pa = &c2; //取地址运算
const complex *pb = &c2; //const取地址运算
return 0;
}
运行结果:
运行后我们发现程序完全ok,并没有错误,所以当我们没定义时,体贴的编译器也会帮我们提供这六种默认成员函数的。