C++实现一个不能被继承的类

构造函数是实现继承的关键,子类对象在构造时,首先调用父类的构造函数,在调用自己的构造函数。

#include <iostream>

using namespace std;

template <typename T>
class A
{
    public:
        friend T;
    private:
        A(){}
        ~A(){}
};

class B:virtual public A <B>
{
    public:
        B(){}
        ~B(){}
};

//class C:virtual public B
//{
//  public:
//      C(){}
//      ~C(){}
//};

int main()
{
    B b;
//  C c;

定义一个友元类friend T,B在继承的时候,用自己去具体化A,将自己设置为A的友元类,这样就可以访问A的私有函数(构造函数),B就可以正常定义对象b,C虚继承B,但是友元关系不能继承。所以C在构造时,不能调用A的构造函数,如果打开注释部分,将报下边的错误。

template.cpp: In constructor ‘C::C()’:
template.cpp:11:3: error: ‘A<T>::A() [with T = B]’ is private
   A(){}
   ^
template.cpp:25:6: error: within this context
   C(){}
      ^
template.cpp:12:3: error: ‘A<T>::~A() [with T = B]’ is private
   ~A(){}
   ^
template.cpp:25:6: error: within this context
   C(){}
      ^
template.cpp: In destructor ‘C::~C()’:
template.cpp:12:3: error: ‘A<T>::~A() [with T = B]’ is private
   ~A(){}
   ^
template.cpp:26:7: error: within this context
   ~C(){}
       ^

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值