Can I stop people deriving from my class?

原创 2007年09月11日 20:07:00
看了Bjarne Stroustrup's的FAQ Can I stop people deriving from my class?
下面总结一下,怎么样阻止派生一个类了,在Java中可以用final关键字,但是在C++中基本上通过下面二种方法:
方法一:
(下面代码在Visual 6.0+windows sp2在运行通过)
#include <iostream>
#include <string>
using namespace  std;

class Derive;

class Base
{
private:
    friend Derive;
    Base()
    {
    }
};

class Derive :public virtual  Base
{
public:
    Derive()
    {   
    }
};

class Test:public Derive
{
};

int main()
{
    Derive A1;
    //Test  A2; //error C2248: 'Base::Base' : cannot access private member declared in class 'Base'
    return 0;
}
其实不是阻止派生一个类,而是阻止了一个类的构造
方法二:
插入一个属性char ch[0];
#include <iostream>
#include <string>
using namespace  std;

class Base
{
public:
    Base()
    {
    }
private:
    char ch[0];
};

int main()
{
    Base A1;
    return 0;
}
虽然这种方法简单,但是存在一个缺点 编译时会警告warning C4200: nonstandard extension used : zero-sized array in struct/union
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

How can I get my public IP address from the command line, if I am behind a router?

24down voteaccepted Assuming your system has 2 ethernet devices, eth0 and eth1 and eth0 is con...

How can I insert a checkbox into the header of my view?

//class MyHeader : public QHeaderView //myheader.h #ifndef MYHEADER_H #define MYHEADER_H #include...

How can I install the Google Apps Package (Play Store, ...) on my Android device?

Background Only Android devices that are licensed by the Open Handset Alliance contain the so cal...

What can I learn right now in just 10 minutes that could be useful for the rest of my life?

What can I learn right now in just 10 minutes that could be useful for the rest of my life?

How can I get a String from HID device in Python with evdev?

http://stackoverflow.com/questions/19732978/how-can-i-get-a-string-from-hid-device-in-python-with-ev...

iOS:编译错误Undefined symbols for architecture i386: _OBJC_CLASS_$_XXX", referenced from: error

Undefined symbols for architecture i386: _OBJC_CLASS_$_XXX", referenced from: error 这个意思为无法找到名为XX...

Undefined symbols for architecture i386:和"_OBJC_CLASS_$_xx", referenced from:问题解决方法

多个人共同操作同一个项目或拷贝项目时,经常会出现类似这样的问题: Undefined symbols for architecture i386: "_OBJC_CLASS_$_xx文件名", r...

Undefined symbols for architecture i386:和"_OBJC_CLASS_$_xx", referenced from:问题解决方法

多个人共同操作同一个项目或拷贝项目时,经常会出现类似这样的问题: Undefined symbols for architecture i386: "_OBJC_CLASS_$_xx文件名...

Undefined symbols for architecture i386:和"_OBJC_CLASS_$_xx", referenced from:问题解决方法

原文地址:http://blog.csdn.net/azhou_hui/article/details/18312047版权声明:本文为博主原创文章,未经博主允许不得转载。多个人共同操作同一个项目或拷...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)