using namespace std;
class PersonA{
private:
PersonA(){cout << "PersonA cconstr called" << endl;};
public:
PersonA* createInstance(){
cout << "Instance created" << endl;
return new PersonA;
};
};
int main()
{
PersonA* Hello = PersonA::createInstance();
return 0;
}
我的IDE给我一个错误,提示: 不带参数调用非静态成员函数 我不明白为什么该方法需要一个参数? 我想念什么吗?
答案 0 :(得分:1)
您可以像-
#include <iostream>
using namespace std;
class PersonA{
private:
PersonA(){cout << "PersonA cconstr called" << endl;};
static PersonA* p;
public:
static PersonA* createInstance(){
if(p == nullptr)
{
cout << "Instance created" << endl;
p= new PersonA();
}
return p;
};
};
PersonA* PersonA::p=nullptr;
int main()
{
PersonA* A = PersonA::createInstance();
PersonA* B = PersonA::createInstance();
return 0;
}
答案 1 :(得分:1)
static
丢失。
但是您当前不实现单例模式,如果需要,请使用Meyers的模式:
class PersonA
{
private:
PersonA() { std::cout << "PersonA constr called" << std::endl;}
public:
PersonA(const PersonA&) = delete;
PersonA& operator =(const PersonA&) = delete;
static PersonA& getInstance(){
static PersonA instance{};
return instance;
}
};
但是也许您只需要一个工厂方法,然后避免原始拥有指针,而使用智能指针:
class PersonA{
private:
PersonA() { std::cout << "PersonA constr called" << std::endl;}
public:
std::unique_ptr<PersonA> create()
{
std::cout << "Instance created" << std::endl;
return std::make_unique<PersonA>();
}
};