【问题标题】:Making class constructor private [duplicate]使类构造函数私有[重复]
【发布时间】:2016-09-11 10:23:07
【问题描述】:

我正在用 C++ 编写一个简单的垃圾收集器。我需要一个单例类 GarbageCollector 来处理不同类型的内存。 我使用了 Meyer 的单例模式。但是当我尝试调用实例时,出现错误:

 error: ‘GarbageCollector::GarbageCollector(const GarbageCollector&)’ is private
    GarbageCollector(const GarbageCollector&);
    ^

这是类定义。

class GarbageCollector //Meyers singleton (http://cpp-reference.ru/patterns/creational-patterns/singleton/)
{
 public:
    static GarbageCollector& instance(){
        static GarbageCollector gc; 
        return gc; 
    }   
    size_t allocated_heap_memory;
    size_t max_heap_memory;
private:
    //Copying, = and new are not available to be used by user.
    GarbageCollector(){};
    GarbageCollector(const GarbageCollector&);
    GarbageCollector& operator=(GarbageCollector&);
};

我使用以下行调用实例: auto gc = GarbageCollector::instance();

【问题讨论】:

  • 在您的class 中有一条评论:Copying,[...] are not available [...]。您收到错误是因为您正在复制 gc
  • 错误消息GarbageCollector(const GarbageCollector&); 中所说的一切都是私人的。您不能从类外部调用私有构造函数。
  • @Elyasin:不是所有的。令人惊讶的是auto 变量被声明为GarbageCollector,而不是GarbageCollector&
  • 鉴于您使用的是auto,您不妨删除复制构造函数和赋值,而不仅仅是将它们声明为私有 - 然后您甚至无法复制 inside类。

标签: c++ oop c++11 constructor auto


【解决方案1】:

改变

auto gc = GarbageCollector::instance();

auto& gc = GarbageCollector::instance();

否则gc不是引用,那么返回的GarbageCollector需要被复制,但是复制的ctor是私有的,这就是编译器报错的原因。

【讨论】:

    猜你喜欢
    • 2011-06-06
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 2015-06-18
    • 2011-04-20
    相关资源
    最近更新 更多