C ++ Faq 23.11 How can I set up my class so it won't be inherited from? 列出以下代码:
class Fred;
class FredBase {
private:
friend class Fred;
FredBase() { }
};
class Fred : private virtual FredBase {
public:
...
};
我试图为它制作一个通用模板。
#include <stdio.h>
template<typename MAKE_ME_NONINHERITABLE >
class NonInheritable{
private:
NonInheritable(){
}
friend MAKE_ME_NONINHERITABLE; //<--- error here
};
这给我一个错误:
xxx.cpp:11: error: a class-key must be used when declaring a friend
所以我试过了:
template<typename MAKE_ME_NONINHERITABLE >
class NonInheritable{
private:
NonInheritable(){
}
friend class MAKE_ME_NONINHERITABLE; //<--- error here
};
class A : virtual public NonInheritable<A>{
};
我收到了这个错误:
xxx.cpp:11: error: using typedef-name `MAKE_ME_NONINHERITABLE' after `class'
有没有办法让这项工作?
答案 0 :(得分:3)
您可以使用c ++ 11中的final
或c ++的microsoft扩展中的sealed
。