简体   繁体   中英

initialize private static variable c++

i want to create a Connector class that holds exactly one sql::Connection Pointer. My attempt was to build a singleton Class and make the pointer and constructor itself private. only a static function is public that is allowed to create the connection.

My attempt to use

Connector::conn = 0;

in the implementation module failed since conn is private and not accessable from outside.

If i ommit initiliziation i get an undefined reference error

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;
}

Instead of

Connector::conn = 0;

write

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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