c++ - 为什么在实现单例类时得到 "Undefined reference error"?

标签 c++ singleton

<分区>

我正在尝试实现一个返回该类实例的方法,但它在第一次尝试创建实例时崩溃了。我不知道如何在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();
}

卡罗.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

最佳答案

您缺少定义 static Carta* m_instance;,因此出现链接器错误:

    Carta* Carta::m_instance = nullptr;

不过我更愿意推荐this pattern ,如果你真的确定你需要一个单例:

static Carta* getInstance() {
    static Carta m_instance;
    return &m_instance;
}

static Carta& getInstance() {
    static Carta m_instance;
    return m_instance;
}

同样为了访问单例,你应该有一些类似的代码

Carta* nueva = Carta::getInstance();
nueva->setColor("rojo");
cout << nueva->getColor() << endl;

或引用版本

Carta& nueva = Carta::getInstance();
nueva.setColor("rojo");
cout << nueva.getColor() << endl;

关于c++ - 为什么在实现单例类时得到 "Undefined reference error"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36582591/

相关文章:

node.js - Node + ES6 类 : Setting up a set of cached objects

没有参数或可执行代码的 PHP 构造函数

C++单例模板类

c++ - getinstance() 在单例中到底做了什么?

c++ - 运算符重载实现 : 0xC0000005: Access violation reading location

c++ - A* 和 N-Puzzle 优化

c++ - Visual Studio 2013 CTP 是否支持非整数类型的类内静态常量初始值设定项?

c++ - 在 heapsort 程序中出现 sigabrt 错误

c++ - 将 std::array<char, 10> 的最后一个字符转换为 int

c# - 在单例类中引用私有(private)单例属性