c++学习之路:基础知识的重构与进阶(一)
c++学习之路:封装性、继承、多态性
c++学习之路:STL初探——以思维导图形式
c++学习之路:基础知识的重构与进阶(二)
c++学习之路:基础知识的重构与进阶(三)
1. 头文件与类的声明
头文件的基本结构
complex.h
#ifndef __COMPLEX__
#define __COMPLEX__
//0.前置声明
class ostream;
class complex;
complex& __doapl(complex* ths, const complex& r);
//1.类的声明
class complex
{
...
};
//2.类的定义
complex::function...
#endif
类的声明
template<typename T> //模板T
class complex
{
public:
complex(T r = 0, T i = 0):re(r), im(i) {} //构造函数+初值列
complex& operator += (const complex&); //操作符重载
T real() const { return re; }
void real(T r) { re = r; } //函数的重载
T imag() const { return im; } //常量成员函数
private:
T re, im;
friend complex& __doapl(complex*, const complex&); //友元函数
};
//构造函数模板的调用
{
complex<double> c1(2.5, 1.5);
complex<int> c2(2, 6);
}
2. 函数
构造函数
class complex
{
public:
complex(double r = 0, double i = 0):re(r), im(i) {} //构造函数+初值列
private:
double re, im;
};
tips:
- 构造函数使用初值列更优雅。
- 构造函数可以被重载,但是要注意有默认形参时,重载函数是否和已有的函数产生二义性。
- 构造函数一般不放在private中,但也有例外。如设计模式Sinleton。
常量成员函数
class complex
{
public:
complex(double r = 0, double i = 0):re(r), im(i) {} //构造函数+初值列
double real() const { return re; } //real()不会改变数值的值,所以要加上const
double imag() const { return im; }
private:
double re, im;
};
//
{
const complex c1(2,1); //构造常量c1
cout << c1.real(); //此时若real()没有const约束,而c1又是常量,会报错
cout << c1.imag();
}
tips:
如果函数不会改变数据的值,一定要加上const。
引用
参数/返回值传递的三种方法:
- 值
complex(double r = 0, double i = 0):re(r), im(r)) {}
- 引用
ostream& operator << (ostream& os, const complex& x){...}
- 常量的引用
complex& operator += (const complex&);
tips:
- 参数/返回值传递尽量都传递引用
- 如果函数的返回值是函数中新创建的对象(临时对象),则不可以返回引用。
- 传递者无需知道接收者是以引用方式接收。
如,
inline complex& __doapl(complex* this, const complex& r)
{
...
return *this;
}
友元
class complex
{
public:
complex(double r = 0, double i = 0):re(r), im(i) {} //构造函数+初值列
complex& operator += (const complex&); //操作符重载
private:
double re, im;
friend complex& __doapl(complex*, const complex&); //友元函数
};
inline complex& __doapl(complex* ths, const complex& r)
{
ths->re += r.re; //自由取得friend的private成员
ths->im += r.im;
return *ths;
}
tips:
- 友元函数可以自由取得friend的private成员
- 相同class的各个对象互为友元
静态数据 & 静态成员函数
class Account
{
public:
static double m_rate;
static void set_rate(const double& x);
};
double Account::m_rata = 8.0; //静态数据的定义
{
Account::set_rate(5.0); //通过对象调用静态函数
Account a;
a.set_rate(7.0); //通过类名调用静态函数
}
tips:
- 静态数据一定要记得定义(初始化)。
- 调用静态函数(通过对象;通过类名)。
3. 操作符重载
- 成员函数(有this指针)
incline complex& __doap1(complex* ths, const complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
incline complex& complex::operator += (const complex& r)
{
return __doapl (this, r);
}
//调用
{
complex c1(2, 1);
complex c2(5);
comples c3(6);
c2 += c1; //+= 作用到c2,c2作为this指针传入操作符重载函数,c1作为参数传入
c3 += c2 += c1;
}
- 非成员函数(无this指针)
#include <iostream.h>
ostream& operator << (ostream& os, const complex& x)
{
return os << '(' << real(x) << ',' << imag(x) << ')';
}
{
complex c1(2, 1);
cout << c1;
}