class Temp
{
private:
~Temp() {}
friend class Final;
};
class Final : virtual public Temp
{
public:
void fun()
{
cout<<"In base";
}
};
class Derived : public Final
{
};
void main()
{
Derived obj;
obj.fun();
}
上面的代码试图实现非可继承类(最终)。 但是,使用上面的代码产生的对象仍然可以创建,为什么呢?
只有在构造函数为私有实现所需的功能,我的问题是,为什么它是无法实现的析构函数私有的情况下?
那么,对于这个节目(pleasse提供正确,编译例子)
#include <iostream>
class Temp
{
private:
~Temp() {}
friend class Final;
};
class Final : virtual public Temp
{
public:
void fun() { std::cout<<"In base"; }
};
class Derived : public Final {};
int main() {
Derived obj;
obj.fun();
}
科莫网上说
Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing. All rights reserved.
MODE:strict errors C++ C++0x_extensions
"ComeauTest.c", line 16: error: "Temp::~Temp()" (declared at line 6) is inaccessible
class Derived : public Final {
^
detected during implicit generation of "Derived::Derived()" at line
21
"ComeauTest.c", line 16: error: "Temp::~Temp()" (declared at line 6) is inaccessible
class Derived : public Final {
^
detected during implicit generation of "Derived::~Derived()" at line
21
2 errors detected in the compilation of "ComeauTest.c".
因为,有疑问时,我总是相信科莫(我只发现过一个错误,但是许多其他的编译器),我想VC9(它接受的代码)是错误的。 (从这个void main()
我想你使用VC,太)。
需要注意的是使用在C ++ 11存在非继承类final
关键字,在之前规定: base1, base2, ..., baseN
继承列表或开幕前{
如果该类从一无所有继承:
class Final final { };
class Derived : public Final { }; // ERROR
随着一点点的宏观魔术和一些编译器检测工作这个可以抽象出来工作,或在最坏的情况做什么,在所有的编译器。
奇异递归模板模式。 使用专用的传承。
template< typename T > class Final
{
protected:
Final() {}
Final( Final const& ) {}
};
class X : private virtual Final<X>
{
// whatever I want to do
};
你应该找到,因为虚拟的传承意味着最派生类必须构建基类,但它不会有任何访问就不可能获得来自X什么。
(我没有测试此代码)。
C ++的常见问题描述不同的方式来实现这一点-但你的问题,我想你已经读过他们。 ;-)
(另外, main
必须始终返回int
,从来void
。)
当然还有正确的方法今天要做的是使用的final
关键字。 例如:
class Foo final {
public:
Foo() {}
~Foo() {}
void bar() {
// ...
}
};
派生类不调用基类的析构函数私有的,因此它不需要可视性。
让你的构造私有的,只能提供静态生成器功能。
我已经修改了原来的代码发布,并证实在G ++这样的代码:
class Temp
{
private:
Temp() {
cout << "In Temp Class ctor" << endl;
}
~Temp() {}
friend class Final;
};
class Final : virtual public Temp
{
public:
void fun()
{
cout<<"In base";
}
};
class Derived : public Final
{
};
int main()
{
Derived obj;
obj.fun();
return 0;
}
结果:$克++ one.cpp -o一个-lm -pthread -lgmpxx -kgmp -lreadline 2>&1
one.cpp:在构造 '衍生::派生()':one.cpp:8:9:错误:温度::温度()'是私有的温度(){
one.cpp:25:11:错误:在此背景下派生类:公共决赛
one.cpp:11:9:错误:温度::〜温度()'是私人〜温度(){}
one.cpp:25:11:错误:在此背景下派生类:公共决赛
one.cpp:11:9:错误:温度::〜温度()'是私人〜温度(){}
注:这是一个最好的做法不使用无效与“主”。
谢谢,