本篇博文以一个简单的例子来讲述C++重点基础,应该适合有一点C++基础的童鞋。
涉及:构造函数,运算符重载,inline(内联)函数,friend(友元)函数,this指针,参数传递和返回值选型,临时对象
- 构造函数:
- 与类名相同,创建object时首先运行的函数
- 初始化方式很多,可以在函数体内{ }赋值的方式初始化,也可以采用初始化列表的方式(建议采用)
- 运算符重载 关键字 operator描述,并不是所有的运算符都可以重载,限制自行查阅
- 在class body 已经实现的函数,比如real imag 默认就是inline函数
- 在定义任何一个函数时,需要考虑到函数是否需要用const描述,主要看函数的作用是否会更改private data
- 传入的参数也要注意是否用const描述,主要看参数是否会发生改变
- 熟悉使用const描述,会给code添加一些自行判断是否出错
- 友元函数:可以打破封装直接访问private data
- 成员函数、全局函数
- 成员函数:在class body 声明的
- 成员函数也可以成为inline函数,inline 描述符,最后是否成为内联函数,要看编译器的判断
- this 指针
- 谁调用就指向谁,比如 C1+=C2 C1调用"+="那么this指针就默认指向C1,一般情况左侧是this
- 参数传递和返回值类型的选择
- 参数传递有两种方式
- by value: 值的方式传递
- by reference: 引用传递,形式"XXX&",占4个字节,传递速度快,类似指针但不是,推荐使用
- by point:指针传递
- 返回类型
- void:空
- int...:变量类型
- xxxx&:reference 引用
- int*:指针
- 参数传递有两种方式
- 全局函数
- 和成员函数相比,没有this 指针
- 返回值肯定不能是by reference,因为返回的是一个local object
- 在这个函数中 inline complex operator + (const complex& x,const complex& y) 实际返回的是一个临时变量由complex( )创建
- 在这个函数inline complex& complex::operator +=(const complex& r)能返回reference,是因为C1+=C2,C1是已经存在的object
complex.h
#ifndef __COMPLEX__
#define __COMPLEX__
class complex
{
public:
complex(double r=0,double i=0)//pass by value
:re(r),im(i)
{}
//构造函数初始化列表方式初始化data
complex& operator += (const complex&);//by reference
//参数传递和返回类型
double real() const {return re;}//在class已经实现的是inline function
double imag() const {return im;}
//在设计任何函数时,要考虑这个函数是否加const,关键是看这个函数是否会更改private data
~complex(){};
private:
double re,im;
/*
友元函数,可以直接调用private data,不需要通过其他函数来取private data
友元函数可以打破封装
相同class的各个object相互为friend 友元
*/
friend complex& __doapl (complex*,const complex&);
};
#endif
complex.cpp
#include "complex.h"
#include <iostream>
using namespace std;
/*
by value by reference
在C++编程中 参数传递和返回值 尽量使用by reference,类似指针,可以加快运行速度,占4个字节
*/
//操作符重载是成员函数或者全局函数
/*成员函数*/
inline complex&
__doapl(complex* ths,const complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
/*
operator += 实际上有两个参数,右边加在左边,左边是调用者,右边的是不会变的,所以是const pass by refrence
返回值 也是refrence,也申明成inlien函数,但是最后是不是inline要看编译器的判断
*/
inline complex&
complex::operator +=(const complex& r)
{
//this 指针指向调用者,左边
return __doapl(this,r);
}
//全局函数,左右都不会改变,产生的新值不是local,不能return referen
//复数+复数,复数+实数,实数+复数
inline complex
operator + (const complex& x,const complex& y)
{
//创建对象可以用complex( ) 创建一个临时对象,也可以complex z
return complex(x.real()+ y.real(),
x.imag() + y.imag());
}
inline complex
operator + (const complex& x,double y)
{
//创建对象可以用complex( ) 创建一个临时对象,也可以complex z
return complex(x.real() + y,x.imag());
}
inline complex
operator + (double x,const complex& y)
{
//创建对象可以用complex( ) 创建一个临时对象,也可以complex z
return complex(x + y.real(),y.imag());
}
ostream&
operator << (ostream& os,const complex& x)
{
return os << '(' << x.real() << ',' << x.imag() <<')';
}
int main()
{
double DD = 12.36;
complex AA(10,20);
complex BB(30,20);
cout << AA << endl;
cout << AA + DD << endl;
cout << DD + BB << endl;
// AA+=BB;
cout << (AA+=BB) << endl;
}