C++面向对象基础(1)-Complex class(不带指针)

头文件与类的声明

标准库以头文件的形式 存在,只需要include进去就好#include <*.h>
头文件的布局:

#ifndef __complex__
#define __complex__

  *******
##endif

class的布局:header+body

构造函数

  1. inline函数:只要成员函数在class body里面定义,不需要显示声明,就是inline函数,而如果在body之外定义,要想成为inline函数,必须显示声明。是否成为inline函数,由编译器来决定,即使声明为inline function,也不一定编译器有能力使之成为inline function。
  2. 创建对象写法:
complex c1(2,1); //创建的时候赋值
complex c2; //默认初值
comlex* p = new complex(4); //动态创建,得到的是指针
  1. 构造函数:没有返回值,可以设默认值,初始列赋值规范如下:
complex (double r = 0, double i = 0)
  : re (r), im (i)   //初始化
{ }                  //赋值

函数重载:函数重载是指在同一作用域内,可以有一组具有相同函数名,不同参数列表的函数,这组函数被称为重载函数。
构造函数放在private里:典型——单例模式

class A {
public:
  static A& getInstance();
  setup () { ... }
private:
  A ();
  A(const A& rhs);
  ...
};

A& A::getInstance ()
{
  static A a;
  return a;
}

调用时A::getInstance() .setup()

常量函数const

当设计接口时要考虑是否允许data被改变,若不改变,则加“const”,如;

double real () const { return re; }
double imag () const { return im; }

若不加"const",后续创建对象时加了“const”关键字,如:

{
  const complex c1(2,1)
  cout << c1.real () ;
  cout << c1.imag () ;
}

编译器会报错重启。
传参:pass by value or pass by reference(to const)
传值:整个传过去(值有多大就传多大) ,举例:

complex (double r = 0, double i = 0)
 : re (r), im (i)
{ }

传引用:相当于C语言的传指针 ,举例:

complex& operator += (const complex&);  

这里加const是为了传引用给别人的时候避免被别人修改值。尽量传引用,当不希望别人修改时就加const。
当局部变量传参时不能传引用,因为当函数结束后,局部变量就会消失

friend 友元函数

可以自由获取private里的成员

操作符重载

成员函数——在类中定义的函数
复数“+=”重载举例:

inline complex&
_doapl (complex* ths, const complex& r)
{
  ths->re += r.re;
  ths->im += r.im;
  return *ths;    // 传递者无需知道接收者是用reference形式接收的
}

inline complex&     // 返回不为空是考虑连续赋值的情况,如:c3 += c2 += c1
complex::operator += (const complex& r)
{
  return _doapl (this, r); //this表示左值,编译器默认的,在函数参数里不能写
}

非成员函数——普通函数,不在类中定义的函数,如友元函数
复数+复数重载举例:

inline complex
operator + (const complex& x, const complex&)
{
  return complex (real (x) + real (y),
                  imag (x) + imag (y));  //返回的是新创建的局部变量,所以不能pass by reference
]

临时对象:typename (),举例:complex(4),临时对象的生命只维持到下一行

复数操作符<<重载

#include <iostream.h>
ostream&
operator << (ostream& os, const complex& x)
{
  return os << '(' << real (x) << ',' << imag (x) << ')';
}

注意<<重载只能是非成员函数 ,且os参数前不能加const关键字,因为每一次<<都需要改变os的值

小结

设计一个class时,注意以下四点:
1、构造函数尽量使用初始列;
2、数据一定放在private里;
3、参数和返回值尽可能传引用,不能传引用时就传值;
4、类的本体里该加const的地方要加,避免使用者加const后报错;

posted @ 2022-03-22 20:31  Stella77  阅读(71)  评论(0)    收藏  举报