C++ note

 

cc

复制构造函数 & 赋值构造函数

只有单个行参,而且该形参是对本类类型对象的引用(常用const修饰),即为复制构造函数,一种特殊的构造函数。

赋值是二元运算,所以该操作符有两个形参,第一个对应着左操作数,第二个对应着右操作数。当操作符为成员函数时,它的第一个操作数隐士绑定到this指针,右操作数一般作为const引用传递。赋值操作符的返回类型应该与内置类型运算返回的类型相同,内置类型的赋值运算一般返回对右操作数的引用,因此,赋值操作符也返回对同一类型的引用。

class C {
private:
    C(const C &); // Disable copy
    C & operator = (const C &); // Disable assign
};

Google C++ Style Guide

  • 函数超过10行时不要使用內联
  • -inl.h內联函数实现文件 | 定义函数模板
  • 输入:const型,输出参数:指针
  • 最好给纯接口类加上Interface后缀
  • 名称为foo_的变量其访问函数为foo(),而其修改器(mutator)则为set_foo(),访问器常在头文件中定义为内联函数。
  • 请按下面的规则次序来定义类:公共成员位于私有成员前;方法位于数据成员前(变量)等等。
  • scoped_ptr | shared_ptr
  • 使用cpplint.py来检测风格错误
  • 类型转换(Casting),需要类型转换时请使用static_cast<>()
  • 类成员以下划线结束 int val_;
  • 禁止使用异常
  • 常量命名, 在名称前加k:kDaysInAWeek
  • 函数形式参数位置和花括号位置

Google CC Guide

标准库比较接口

  • 函数形式
int compare(int a, int b) {
    return a < b;
}
  • 函数对象
struct Node {
	int left, right, parent;
	int w;
	char ch;
	int id;
	Node(): left(-1), right(-1), parent(-1), w(0) {}
    Node(int l, int r, int ww): left(l), right(r), w(ww), parent(-1) {}
};

struct NodeCmp {
	bool operator () ( const Node *n1, const Node *n2 ) {
		return n1->w > n2->w;
	}
};
priority_queue<Node *, vector<Node *>, NodeCmp> que;
  • 友元形式
struct Distance {
	int node_id;
	int dis;
	friend bool operator < (Distance d1, Distance d2) {
		return d1.dis > d2.dis;
	}
	Distance() {}
};
priority_queue<Distance> que;