我有一个单身人士,例如:
#include <bits/stdc++.h> class A { private: A() {printf("init a unparam A\n");} virtual ~A() = default; public: static A& Inst() { static A u; return u;} void print() {printf("my no = %d\n", no_);} int no_ = -1; };
我知道这很奇怪,在大多数情况下,我的程序中只需要一个。但在某些情况下,我需要在一个程序中包含多个对象,因此我添加了一个带 int 的构造函数。
#include <bits/stdc++.h> class A { private: A() {printf("init a unparam A\n");} A(int i) : no_(i) { printf("init a A with no = %d\n", no_);} // this part is added virtual ~A() = default; public: static A& Inst() { static A u; return u;} static A& Inst(int i) { static A u(i); return u;} // added void print() {printf("my no = %d\n", no_);} int no_; };
在 main.cpp 中:
int main() { A & a = A::Inst(); a.print(); A & b = A::Inst(1); b.print(); A & c = A::Inst(2); c.print(); }
结果是:
init a unparam A my no = 0 init a A with no = 1 my no = 1 my no = 1 // Inst(2) only get the Inst(1) object, why?
在我的选项中,第一个 a 将a通过调用一个无参数的构造函数来创建Inst,b将创建一个 no=1,c创建一个 no=2。但真正的结果是,b和c共享一个对象。你能帮忙吗?我怎样才能做到这一点?