一:使用final(c++11)
二:构造函数通过private修饰,但是这个时候,是无法在栈上创建对象的,只能是借助于静态成员函数在堆上创建对象。
三:friend+虚继承
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class A
{
private:
A(int i = 10):m_a(i)
{
cout<<"A()"<<endl;
}
friend class B;
public:
int m_a;
};
class B: public A
{
public:
B()
{
cout << "B()" << endl;
}
int m_b;
};
class C:public B
{
public:
C()
{
cout << "C()" << endl;
}
int m_c;
};
int main()
{
B b;
C c;
return 0;
}
上面这段代码当中,定义一个类B对象时,没问题,因为这个时候类B已经是类A的友元类了,所以即使类A的构造函数是private的,定义一个类B对象时,依旧可以调用类A的构造函数。
而类C通过继承类B,这个时候,编译没问题,因为,类C对象一样可以调用类B的构造函数。
那怎么样让类C无法继承类B?
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class A
{
private:
A(int i = 10):m_a(i)
{
cout<<"A()"<<endl;
}
friend class B;
public:
int m_a;
};
class B: virtual public A
{
public:
B()
{
cout << "B()" << endl;
}
int m_b;
};
class C:public B
{
public:
C()
{
cout << "C()" << endl;
}
int m_c;
};
int main()
{
B b;
C c;
return 0;
}
让类A虚继承类B就可以了,这个时候,由于虚继承的原因,所以,定义一个类C对象时,因为类A的构造函数是通过类C来调用的,但是类A的构造函数是private,并且,类C不是类A的友元类,所以,这个时候,类C就继承不了类B了。