美文网首页
勿在浮沙筑高台--P10

勿在浮沙筑高台--P10

作者: Catherin_gao | 来源:发表于2021-01-30 11:08 被阅读0次

扩展补充

一. static

class complex{
public:
   double real() const{
         // return this->re; 
         return re;
    }
private:
    double re, im;
}
complex c1,c2,c3;
cout<< c1.real();
cout<< c2.real();

从C语言的角度,可以解读为:

  • this是对象的地址
complex c1,c2,c3;
cout<< complex::real(&c1);
cout<< complex::real(&c2);

1.1 static成员变量、成员变量

  • static 成员变量是所有对象公有。
  • static 成员变量,没有this。只能处理静态数据。
class Account{
public:
    static double m_rate;    //所有银行账户的利息利率应该是一样的
    static void set_rate(const double& x){m_rate = x;}
};
double Account::m_rate = 8.0;

int main(){
  Account::set_rate(5.0);  //通过class name调用
  
  Account a;
  a.set_rate(7.0);  //通过对象调用
}
  • 调用static函数的方式有二:
    • (1)通过对象调用
    • (2)通过class name调用

1.2 单例模式

  • 构造函数放在private中。
  • 设计public的函数调用唯一的对象a。
  • static 对象放在公有函数定义中。
class A{
public:
    static A& getInstance();
    setup() {...}
private:
    A();
    A(const A& rhs);
    ...
};

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

A::getInstance().setup();

二. 模板

2.1 类模板

template<typename T>
class complex
{
public:
    complex(T r=0, T i=0)
        :re(r), im(r)
    {}
    complex& operator += (const complex&)
    T real() const {return re;}
    T imag() const {return im;}
private:
    T re, im;

    friend complex&   __doapl(complex*, const complex&)

};
{
   complex<double> c1(2.5, 1.5);
   complex<int> c2(2, 6);
   ...
}

2.2 函数模板

template<class T>
inline
const T& min(const T& a, const T& b){
  return b< a? b : a;
}

stone r1(2,3), r2(3,3), r3;
r3 = min(r1, r2);

class stone{
public:
   stone(int w, int h, int we)
       : _w(w), _h(h), _weight(we);
           {   }
    bool operator<(const stone& rhs) const
           {return _weight < rhs._weight; }
private:
    int _w, _h, _weight;
}

三. namespace

相关文章

网友评论

      本文标题:勿在浮沙筑高台--P10

      本文链接:https://www.haomeiwen.com/subject/qkmktltx.html