您的位置:首页 > 编程语言 > C语言/C++

c++模版的一个好玩的特性

2013-01-16 16:32 295 查看
这个代码展示了private继承和模版的一个妙用:

#include <iostream>
#include <memory>

template<typename T>
class Counter {
public:
Counter() { count++; }
Counter(const Counter&) { count++; }
~Counter() { --count; }
public:
std::size_t howMany(void) { return count; }
private:
static std::size_t count;
};

template<typename T>
std::size_t Counter<T>::count = 0;

class B : private Counter<B> {
public:
B() { }
~B() { }
using Counter<B>::howMany;
private:
int val;
};

int main(void)
{
std::auto_ptr<int> pInt(new int(5));

std::cout << *pInt << std::endl;
B b1;
{
B b2;
std::cout << b1.howMany() << " " << b2.howMany() << std::endl;
}

std::cout << b1.howMany() << std::endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: