本文是作者在学习C++面向对象过程中,认为需要注意的部分,
■ 防卫式声明
防止重复引入相同的头文件
#ifdef __xxx__
#define __xxx__
#endif
■ 类中的函数
函数可以重载, 但是形参列表需要不同
int add(int a, int b) {
return a + b;
}
int add(int a) {
return a;
}
当有一个函数形式参数有默认值的时候,重载时候要注意
int add(int a = 0, int b = 0) {
return a + b;
}
//如果写成这样会出错
int add(int a) {
return a
}
当一个函数只是返回属性的值,而没有修改函数的值的时候,我们可以使用const关键字去修饰函数.
int add(int a, int b) const {
return a + b;
}
■ inline函数
当函数写在类的外面但是,某个对象想调用这个函数的时候,我们可以在这个函数前面加上inline
关键字, 并且在类中进行声明
Complex& operator += (const Complex&);
外部声明的inline函数
inline Complex& Complex::operator += (const Complex& r) {
//返回一个对象的引用
return __doapl(this, r);
}
■ 创建对象时候
在创建对象的时候,传入的参数需要和构造函数的形参一致,除非构造函数写了默认值。
Complex (double r = 0, double i = 0)
: re(r), im(i)
{}
■ 传递引用
引用存的是对象的地址,取出确是对象,而指针是存放对象的地址,传递引用很快,所以尽量传递引用, 如果你不想函数修改对象,可以加上const
#ifndef __Test__
#define __Test__
#include <iostream>
using namespace std;
int main() {
int a = 1;
int& inf = a;
cout << inf;
return 0;
}
#endif
什么情况下不可以传递引用:
当一个对象在函数中创建,然后我们返回这个对象的引用,这种是错误的,因为函数结束,这个对象就消失了,所以此时不可以传递引用。
■ 友元
因为封装了对象,所以我们不可以直接使用, 除了使用内部的函数外,我们还可以使用友元
friend Complex& __doapl(Complex*, const Complex&);
inline Complex& __doapl(Complex* ths, const Complex& r) {
ths->re += r.re;
ths->im += r.im;
//对左边的操作
return *ths;
}
各个class之间互为友元
#ifndef __Test__
#define __Test__
#include <iostream>
#include <cstdio>
using namespace std;
class complex {
public:
complex (double r = 0, double i = 0)
: re(r), im(i)
{}
int func(const complex& param)
{return param.re + param.im;}
private:
double re, im;
};
int main() {
complex c1(2, 1);
complex c2;
c2.func(c1);
return 0;
}
#endif