我试图实现一个方法,它返回一个类的实例,但它在第一次尝试创建实例时崩溃.我不知道如何在C++/QT中实现单例
主要
#include <QCoreApplication>
#include "carro.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Carta* nueva;
nueva->getInstance();
nueva->setColor("rojo");
cout << nueva->getColor() << endl;
return a.exec();
}
Run Code Online (Sandbox Code Playgroud)
Carro.h
#ifndef CARRO_H
#define CARRO_H
#include <string>
#include <iostream>
using namespace std;
class Carta{
private:
string cara; //valor
string palo; //simbolo
string color;
string direccion;
static Carta* m_instance;
public:
//constructor
Carta(){
}
static Carta* getInstance(){
if(!m_instance){
m_instance = new Carta;
}
return m_instance;
}
string getDireccion(){
return direccion;
}
void setColor(string pcolor){
color = pcolor;
}
string getColor(){
return this->color;
}
string getPalo(){
return this->palo;
}
string getCara(){
return this->cara;
}
//print
string print(){
return (cara + " de " + palo + " Color: "+color);
}
};
#endif // CARRO_H
Run Code Online (Sandbox Code Playgroud)
您一直缺少定义static Carta* m_instance;,因此链接器错误:
Carta* Carta::m_instance = nullptr;
Run Code Online (Sandbox Code Playgroud)
但是我宁愿推荐这种模式,如果你真的确定你需要一个单身人士:
static Carta* getInstance() {
static Carta m_instance;
return &m_instance;
}
Run Code Online (Sandbox Code Playgroud)
要么
static Carta& getInstance() {
static Carta m_instance;
return m_instance;
}
Run Code Online (Sandbox Code Playgroud)
另外,对于访问单例,您应该有一些代码
Carta* nueva = Carta::getInstance();
nueva->setColor("rojo");
cout << nueva->getColor() << endl;
Run Code Online (Sandbox Code Playgroud)
或与参考vesion
Carta& nueva = Carta::getInstance();
nueva.setColor("rojo");
cout << nueva.getColor() << endl;
Run Code Online (Sandbox Code Playgroud)