如何使用私人构造函数得出基类?
我想设计带有私有构造函数的基类:
#pragma once
#include <bits/stdc++.h>
// base class for singleton
template<typename T>
class Singleton {
public:
virtual ~Singleton() {}
static Singleton& Inst(const T& t) {
const auto & it = ss_map_.find(t);
if (it == ss_map_.end()) { printf("Singleton Inst Failed\n"); exit(1); }
else return *(it->second);
}
static void Malloc(const std::vector<T>& v) {
for (const auto & i : v) ss_map_[i] = new Singleton(i);
}
static void Release() {
for (auto & [_, s] : ss_map_) delete s;
}
static void Release(const T& t) {
const auto & it = ss_map_.find(t);
if (it == ss_map_.end()) { printf("Singleton Release Failed\n"); exit(1); }
delete it->second;
ss_map_.erase(it);
}
protected:
inline static std::unordered_map<const T, Singleton*> ss_map_;
private:
Singleton(const T&) {}
Singleton& operator =(const Singleton&)=delete;
Singleton(const Singleton&) = delete;
Singleton(const Singleton&&) = delete;
};
我将其作为模板类,可以让任何类型的派生类构造。
派生的类看起来像这样:
class A : public Singleton<int> {
friend class Singleton;
private:
A(int a) : Singleton<int>(a) {} // PROBLEM HERE, the complier failed to complie.
}
请参阅《代码: a类A
的构造函数》中的注释,而compleier错误失败了:
基类“ Singleton”具有私人构造函数
我该如何使 a 工作?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已经以错误的方式定义了您的朋友关系。 base类需要声明
类A
一个朋友,以便提供对其私有构造函数的访问:注:另请参阅: Why我不应该#include&lt; lt; stdc ++。
You have defined your friend relationship the wrong way round. The base class needs to declare
class A
a friend in order to provide access to its private constructor:Note: See also: Why should I not #include <bits/stdc++.h>?