繁体   English   中英

初始化私有静态变量c ++

[英]initialize private static variable c++

我想创建一个连接器类,其中仅包含一个sql :: Connection指针。 我的尝试是建立一个单例类,并使指针和构造函数本身私有。 只有静态函数是公共的,允许创建连接。

我尝试使用

Connector::conn = 0;

在实现模块中失败,因为conn是私有的,无法从外部访问。

如果我忽略初始化,则会收到未定义的参考错误

Connector.h

#ifndef CONNECTOR_H
#define CONNECTOR_H

#include <cppconn/driver.h>
#include <cppconn/exception.h>

class Connector {

public:
    static sql::Connection* getConnection();


protected:
    Connector();
    Connector(const Connector& other) { }

    static sql::Connection * conn;
    static sql::Driver * drive;
};

#endif  /* CONNECTOR_H */

Connector.cpp

#include "Connector.h"

Connector::Connector() {
}

sql::Connection * Connector::getConnection() {
    if(Connector::conn == 0) {
        Connector::drive = get_driver_instance();
        Connector::conn = Connector::drive->connect("tcp://any.de:3306", "any", "any");
        Connector::conn->setSchema("cryptoTool");
    }
    return Connector::conn;
}

代替

Connector::conn = 0;

sql::Connection * Connector::conn = 0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM