【2015.09.27】C++学习笔记

一元运算符重载

  • 友元重载与成员重载
    • 友元重载:
1
2
3
4
5
6
7
8
class Aclass()
{
friend bool operator== (Aclass &objectA, Aclass &objectB);
};
bool &operator++(Aclass &object)
{
//do something..
}
  • 成员重载:
1
2
3
4
5
6
7
8
class Aclass()
{
public:
bool operator==(Aclass & objectB)
{
//do something..
}
};
  • 索引运算符[]必须使用成员函数重载
  • ++运算符前置与后置的区分: 前置operator++() 后置operator++(int)

模板

  • 在声明一个 template type parameter(模板类型参数)的时候,class 和 typename 意味着完全相同的东西,可以随意混用。
    • template<typename T> class Widget; // uses "typename"```
      以上完全相同
      
  • 一个 template(模板)中的依赖于一个 template parameter(模板参数)的名字被称为 dependent names(依赖名字)。 当一个 dependent names(依赖名字)嵌套在一个 class(类)的内部时,我称它为 nested dependent name(嵌套依赖名字)。嵌套依赖名字必须显式使用typename关键字声明其为type,否则将不被认为是type。
    • void print2nd(const C& container)
      {
           C::const_iterator * x;
           ...
      }```
      如不使用typename声明,将被认为是C中的static member(静态成员)const_iterator与某个已存在的x进行*运算相乘),如果要声明x为C内的nested dependent name(嵌套依赖名字),必须显式使用:`typename C::const_iterator * x;` [1]
      
  • 模板参数也可以不使用typename而接受普通值,如template<typename C, int value>,可用于类模板,如
1
2
3
4
5
6
template<typename C, int value>
class AClass{
private:
C _aC;
const int _Avalue = value;
};
  • 类模板,成员函数在类声明外定义时,必须在每个函数前加上template信息,例如
1
2
3
4
5
6
7
8
9
10
11
12
13
template<typename C, int value>
class AClass{
public:
void aFunction(int aParm);
private:
C _aC;
const int _Avalue = value;
};

template<typename C, int value>
void AClass<C, value>::aFunction(int aParm)
{
}
  • 模板代码不能分离编译(不能分成.h和.cpp,必须根据需要全部写在.h或.cpp)
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~

支付宝
微信