1.类
类的三个新特征:友元(friend)、可变成员和静态成员。
友元:允许一个类将对其非公有成员的访问权授予指定的函数或类。
2.new与delete
new时做了三件事:①分配内存空间。②调用构造函数。③返回对象指针。
delete时做了两件事:①调用析构函数。②释放内存空间。
3.构造函数
1)实参决定使用哪个构造函数。
2)构造函数自动执行。
3)先调用基类构造函数,再调用子类构造函数。
4)常见类型(无参、拷贝、重载)及调用过程。与等号运算符重载区分。
例1:
#include <iostream>
using namespace std;
class Complex
{
private :
double m_real;
double m_imag;
int id;
static int counter;
public:
// 无参数构造函数
Complex(void)
{
m_real = 0.0;
m_imag = 0.0;
id=(++counter);
cout<<"Complex(void):id="<<id<<endl;
}
// 一般构造函数(也称重载构造函数)
Complex(double real, double imag)
{
m_real = real;
m_imag = imag;
id=(++counter);
cout<<"Complex(double,double):id="<<id<<endl;
}
// 复制构造函数(也称为拷贝构造函数)
Complex(const Complex & c)
{
// 将对象c中的数据成员值复制过来
m_real = c.m_real;
m_imag = c.m_imag;
id=(++counter);
cout<<"Complex(const Complex&):id="<<id<<" from id="<<c.id<<endl;
}
// 类型转换构造函数,根据一个指定的类型的对象创建一个本类的对象
Complex(double r)
{
m_real = r;
m_imag = 0.0;
id=(++counter);
cout<<"Complex(double):id="<<id<<endl;
}
~Complex()
{
cout<<"~Complex():id="<<id<<endl;
}
// 等号运算符重载
Complex &operator=( const Complex &rhs )
{
if ( this == &rhs ) {
return *this;
}
this->m_real = rhs.m_real;
this->m_imag = rhs.m_imag;
cout<<"operator=(const Complex&):id="<<id<<" from id="<<rhs.id<<endl;
return *this;
}
};
int Complex::counter