目录
设计一个不能被继承的类 , 但可以在外部环境创建该类型的对象
设计一个类型,不能在外部环境中创建该类的对象
class Singleton
{
int value;
private: // protected:
Singleton(int x = 0) :value(x) {}
public:
Singleton(const Singleton&) = delete; // c98;
Singleton& operator=(const Singleton&) = delete;
private:
~Singleton() { cout << "~Singleton" << endl; }
public:
static Singleton& getInstance()
{
static Singleton s(10);
return s;
}
//static Singleton sc;
};
设计一个不能被继承的类
class non_herit
{
private:
non_herit() {}
public:
non_herit(const non_herit&) {}
~non_herit() {}
};
class B : non_herit
{
};
int main()
{
//B b;
}
设计一个不能被继承的类 , 但可以在外部环境创建该类型的对象
class non_herit final : public Object
{
int value;
public:
non_herit(int x = 0) :value(x) {}
non_herit(const non_herit&) = default; // delete // c11;
non_herit& operator=(const non_herit&) = default;
~non_herit() = default;
};
设计一个能被继承的类 , 但不能在外部环境创建该类型的对象
class Object
{
private:
int value;
protected:
Object(int x = 0) :value(x) {}
Object(const Object& obj) :value(obj.value) {}
Object& operator=(const Object& obj)
{
if (this != &obj)
{
value = obj.value;
}
return *this;
}
public:
~Object() {}
};
限制派生类对象不可以拷贝和赋值如何实现。
class noncopyable
{
public:
noncopyable() = default;
~noncopyable() = default;
protected:
noncopyable(const noncopyable&) = delete;
noncopyable& operator=(const noncopyable&) = delete;
};