文件与类的声明
Object Based:面对的是单一 class 的设计
Object Oriented:面对的是多重 classes 的设计,classes 和 classes 之间的关系
.h
:中进行 函数、类声明,还有一些是标准库;
.cpp
:中要包含 声明 .h
的声明文件;
输出
#include <iostream>
using namespace std;
int main()
{
int i = 7;
cout << "i = " << i << endl; // 标准输出,直接输出后面的内容,比c语言更加的方便
return 0;
}
头文件的写法
/* complex.h 在写任何一个头文件时必须进行 防卫式的声明(guard) */
#ifndef __COMPLEX__
#define __COMPLEX__
template<typename T> // 模板,可以提高代码的复用性
class Complex { // class 的 头
public: // class 的 身体
Complex (T r = 1, T i = 0) : re(r), im(i) {} // 构造函数可以有默认值
// 构造函数不需要返回类型
// 构造函数初始化列表
Complex () : re(0), im(0) {} // 构造函数运行进行重载 overloading
Complex& operator += (const Complex&); // 函数的声明,类的相加操作符
T real() const { return re; } // 函数的定义,函数本地较为简单,编译器会自动设置为 inline 函数
T imag() const { return im; } // 函数的定义, const 常量成员函数(数据内容不会改变),注意是要加上const
int func(const Complex& para)
{
return para.re + para.im; // 相同class 的各个对象互为friend
}
private:
Complex (); // 构造函数也是可以放到 private 里面,例如单例模式,只允许创建一个对象
T re, im;
friend Complex& __doapl (Complex*, const Complex&); // 声明 __doapl 是 Complex 的友元函数,complex 创建的对象是可以访问的
};
#endif
inline (内联函数)函数
inline Complex& __doapl(Complex *ths, const Complex& r)
{
ths->re += r.re; // 可以自由获取friend的 private 成员
ths->im += r.im;
return *ths; // 返回类型必须是一个对象
}
操作符重载 - 之成员函数 this
操作符相当于一种函数
void test()
{
Complex c1(2, 1);
Complex c2(5);
c2 += c1; // 1. 重载 += 操作符
}
// 2. 实部,虚部各自相加,然后返回一个引用的对象
inline Complex& __doapl(Complex *ths, const Complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths; // 返回类型必须是一个对象
}
// 3. 重载操作符的实现,具体代码里面没有 this,添加 this 是为了方便理解
// 任何一个成员函数都有一个 this pointer
inline Complex& Complex::operator+=(this,const Complex& r)
{
return __doapl (this, r);
}
return by reference 语法分析
传递者 无需知道 接受者 是以 reference 形式接受
// 采用 reference 接收,比 值传递 的速度更快
inline Complex& __doapl(Complex *ths, const Complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths; // 返回是一个对象, 接受者是一个引用,很合理
}