1- C++中类模板,重载等实例
简单的example,包括了模板类的定义,使用。以及拷贝赋值云算法重载的写法。程序是规范写法。
/*************************************************************************
File Name: template.cpp
Author: bin.wang
Mail: sa615168@mail.ustc.edu.cn
Created Time: Sat 11 Feb 2017 10:23:48 AM CST
************************************************************************/
#include <iostream>
using namespace std;
template<typename T>
class Comparator{
public:
Comparator(T x, T y): m_x(x), m_y(y){}
Comparator(Comparator<T> const & that):
m_x(that.m_x), m_y(that.m_y){}
Comparator<T>& operator=(Comparator<T> const& rh)
// Comparator& operator=(Comparator const& rh)
{
this->m_x = rh.m_x;
this->m_y = rh.m_y;
return *this;
}
T max(void) const;
private:
T m_x;
T m_y;
};
template<typename T>
T Comparator<T>::max(void) const{
return m_x > m_y ? m_x: m_y;
}
int main(int argc, char ** argv)
{
Comparator<string> cs("hello","world");
cout << cs.max() << endl;
Comparator<string> ns("wang","bin");
cs = ns;
cout << cs.max()<< endl;
return 0;
}
这个代码很短,但是许多地方值得注意。方便以后查看。
应该规范的地方:1
template<typename T> typename 在c++中虽说可以用class代替。但是typename是最好的。原因很多,不赘述。
应该规范的地方:2
Comparator<T>& operator=(Comparator<T> const& rh)
可以这样写(去掉模板参数)
Comparator& operator=(Comparator const& rh)
这样也可以编译出来结果,就是让编译器推断。我们不可以假设所有的c++编译器都能推断正确。
为了严谨,类模板是不可以定义对象的。
应该规范的地方:3
T max(void) const; //定义max为const function 去除了用户试图修改类中私有成员变量的风险
应该规范的地方:4
Comparator<T>& operator=(Comparator<T> const& rh) //传的参数(常引用)
拷贝赋值运算符的重载,注意返回的类型:自身的引用
2 - 构造函数
2.1 构造函数设置为private的含义?
构造函数设置为private一般是不希望类外的函数/方法 实例化对象。一般单例模式 Singleton Pattern 的写法。
这种写法不允许在栈空间上申请内存,只能在堆空间申请
3 - 析构函数
3.1 虚构函数设置为 virtual ?
4 - 命名空间
5 - 继承与注入
6 - 反射机制
7- 宏
7.1 #
的意义
#define TO_STRING(x) #x
const char *str = TO_STRING( input );// str的内容就是”input“,也就是说#会把其后的符号 直接加上双引号。
7.2 ##
的意义
#define SIGN( x ) INT_##x
int SIGN( 1 ); //宏被展开后将成为:int INT_1;
7.3 log
#define LOG( format, ... ) printf( format, __VA_ARGS__ )
string str = "xxx";
int count = 3;
LOG( "%s %d", str.c_str(), count ); //VA_ARGS是系统预定义宏,被自动替换为参数列表。