总:Classes的两个经典分类
- Class without pointer member(s)
complex - Class with pointer member(s)
string
函数
- 数据和操作是单独处理的。
- 耦合和解耦
.cpp 文件和头文件
- include 标准库的符号是<>
- include 自己的文件的符号是 ""
头文件写法
- 为了能够自由顺序include文件
#ifndef __COMPLEX
#define __COMPLEX
...
#endif
三. complex class的声明
class complex
{
public:
complex(double r=0, double i=0)
:re(r), im(r)
{}
complex& operator += (const complex&)
double real() const {return re;}
double imag() const {return im;}
private:
double re, im;
friend complex& __doapl(complex*, const complex&)
};
inline 函数
- 函数在class内部定义,自动成为inline函数。
- inline仅为对编译器的建议,编译器决定哪个函数inline。
访问级别
public:外界使用函数
private:数据,内部函数
构造函数
- 和类名相同。
- 构造函数只有的初始化方式:初值列,初始列。
- 变量有两个阶段:初始化和赋值。初始列是在变量初始化就设置值。
- 构造函数可以有很多个:重载。
{
complex c1(2, 1);
complex c2;
complex* p = new complex(4);
}
析构函数
- 不带指针的类一般不用写析构函数
重载
- 类中重载经常发生在构造函数中
double real() const {return re;}
void real(double r) {re=r;}
- real函数的编译名字
?real@Complex@@QBEX
?real@Complex@@QBEXNU
complex(double r=0, double i=0)
:re(r), im(r)
{}
comple():re(0), im(0){} //不可以,编译会不知道调用哪一个,complex c1();
函数加const
- 不改变参数,应该加const
double real() const {return re;}
double imag() const {return im;}
- 函数不加const,const对象调用会出问题。
{
const complex c1(2,1);
cout<< c1.real();
cout<< c1.img();
}
参数传递: pass by value vs. pass by reference(to const)
complex& operator += (const complex&);
pass by value: 全部打包传过去,使用栈。
pass by reference:传输的内容过大,可以传引用。引用的底层就是一个指针,像传指针一样快。
返回值的传递尽量用引用: 不能用内部变量。
友元 (friends)
- 自由取private成员
相同class的各个objects互为友元
class complex
{
public:
complex(double r=0, double i=0)
:re(r), im(r)
{}
int func(const complex& param)
{ return param.re +param.in; }
private:
double re, im;
};
{
complex c1(2,1);
complex c2;
c2.func(c1);
}
操作符重载--成员函数
- 操作符是一种函数。
- return by reference: 传递者不需要知道接受者是以reference形式接收。
- 封装了一层函数__doapl。
inline complex& __doapl(complex* ths, const complex& r){
ths->re += r.re;
ths->im += r.im;
return *ths;
}
inline complex&
complex::operator += (const complex& r){
return __doapl(this, r);
}
{
complex c1(2, 1);
complex c2(5);
c2 += c1;
}
- 连续赋值需要 返回值类型为'complex&'.
c3 += c2 += c1;
- '+=' 操作符作用在'c2'上。编译器符号作用在左边。
inline complex&
complex::operator += (this, const complex& r){
return __doapl(this, r);
}
操作符重载--非成员函数
- 全局函数,没有this指针。
- 不能使用return by reference,因为他们返回的必定是local object。
- typename(): complex()
inline complex
operator + (const complex& x, const complex& y){
return complex(real(x) + real(y), imag(x)+imag(y));
}
整体代码
#ifndef __COMPLEX
#define __COMPLEX
class complex
{
public:
complex(double r=0, double i=0)
:re(r), im(r)
{}
complex& operator += (const complex&)
double real() const {return re;}
double imag() const {return im;}
private:
double re, im;
friend complex& __doapl(complex*, const complex&)
};
#endif
inline complex&
__doapl(complex* ths, const complex& r){
ths->re += r.re;
ths->im += r.im;
return *ths;
}
inline complex&
complex::operator += (const complex& r){
return __doapl(this, r);
}