1.conversion function,转换函数
class Fraction
{
public:
Fraction(int num, int den=1) //non-explicit-one-argument-ctor
: m_numerator(num), m_denominator(den) {}
operator double() const {
return (double) (m_numerator / m_denominator);
}
private:
int m_numerator; //分子
int m_denominator; //分母
};
Fraction f(3,5);
double d = 4+f; //调用operator double将 f 转为 0.6
2.non-explicit-one-argument-ctor
class Fraction { public: Fraction(int num, int den=1) : m_numerator(num), m_denominator(den) {} Fraction operator+ (const Fraction& f) { return Fraction(...); } private: int m_numerator; int m_denominator; }; Fraction f(3,5); Fraction d2 = f+4; //调用 non-explicit ctor 将 4 转为 Fraction(4,1) //然后调用operator+3.conversion function vs. non-explicit-one-argument-ctor
class Fraction
{
public:
Fraction(int num, int den=1)
: m_numerator(num), m_denominator(den) {}
operator double() const {
return (double) (m_numerator / m_denominator);
}
Fraction operator+ (const Fraction& f) {
return Fraction(...);
}
private:
int m_numerator;
int m_denominator;
};
Fraction f(3,5);
Fraction d2 = f+4; //[Error]ambiguous 歧义
4.explicit-one-argument-ctor
class Fraction
{
public:
explicit Fraction(int num, int den=1)
: m_numerator(num), m_denominator(den) {}
operator double() const {
return (double) (m_numerator / m_denominator);
}
Fraction operator+ (const Fraction& f) {
return Fraction(...);
}
private:
int m_numerator;
int m_denominator;
};
Fraction f(3,5);
Fraction d2 = f+4; //由于构造函数有explicit, 4不能转换成Fraction,所以失败
5.pointer-like classes,关于智能指针
template6.member template,成员模板class shared_ptr { public: T& operator*() { return *px; } T* operator->() { return &px; } shared_ptr(T* p) :px(p) {} private: T *px; long* pn; .... }; struct Foo { void method(void) {} }; { shared_ptr sp(new Foo); Foo f(*sp); sp->method(); }
template
struct pair {
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair()
: first(T1()), second(T2()) {}
pari(const T1& a, const T2& b)
: first(a), second(b) {}
template
pair(const pair& p)
: first(p.first), second(p.second) {}
};
T1 T2 U1 U2
pairp1(pair)
7.specialization,模板特化
template
struct hash {};
template<>
truct hash {
size_t operator()(char x) cosnt { return x; }
};
template<>
struct hash {
size_t operator()(int x) const { return x; }
};
template<>
struct hash {
size_t operator()(long x) const { return x; }
};
8.template template parameter,模板模板参数
template
class Smartptr
>
class XCls
{
private:
Smartptr sp;
public:
XCls() : sp(new T) {}
};