我想通过继承Db来创建抽象的Db类并实现Pg(postgresql):
Db.h :
template <class T>
class Db
{
public:
Db(std::string, std::string, std::string, std::string);
virtual ~Db();
protected:
T* getConnection();
std::string getHost();
std::string getUsername();
std::string getDatabase();
std::string getPassword();
virtual std::string getConnectionString()=0;
private:
T* connection;
std::string host;
std::string username;
std::string database;
std::string password;
};
Db.cpp :
#include "Db.h"
using namespace std;
template <class T>
Db<T>::Db(string iHost, string iUsername, string iDatabase, string iPassword)
: host(iHost), username(iUsername), database(iDatabase), password(iPassword) {
T* conn(getConnectionString());
connection = conn;
}
template <class T>
T* Db<T>::getConnection() {
return connection;
}
... getters
Pg.h :
#include "../Db.h"
template <class T>
class Pg : public Db<T> {
public:
virtual std::string getConnectionString();
};
Pg.cpp :
#include "Pg.h"
template <class T>
std::string Pg<T>::getConnectionString() {
return "host=" + this->getHost() + " user=" + this->getUsername()
+ " password=" + this->getPassword() + " dbname=" + this->getDatabase();
}
的main.cpp :
#include <iostream>
#include <pqxx/connection>
#include <pqxx/transaction>
#include "lib/db/pg/Pg.h"
using namespace std;
int main () {
string host = "localhost";
string username = "username";
string database = "db";
string password = "root";
try {
Pg<pqxx::connection> *db(host, username, database, password);
} catch (pqxx::broken_connection) {
cout << "Failed to establish connection." << endl;
}
return 0;
}
很抱歉长期实施。用g ++编译后我得到一个错误:
main.cpp: In function ‘int main()’:
main.cpp:15:62: error: expression list treated as compound expression in initializer [-fpermissive]
Pg<pqxx::connection> *db(host, username, database, password);
^
main.cpp:15:62: error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘Pg<pqxx::basic_connection<pqxx::connect_direct> >*’ in initialization
我不知道最后是不是一个好主意,因为我的第一个版本只有main()函数看起来更紧凑。我只是尝试在某处隐藏连接细节,例如连接字符串。
答案 0 :(得分:0)
在main()
中,您的db
变量被声明为指针。您不能像以前那样将构造函数参数传递给指针。
您需要:
从声明中删除*
:
Pg<pqxx::connection> db(host, username, database, password);
保留*
并使用new
构建对象:
Pg<pqxx::connection> *db = new Pg<pqxx::connection>(host, username, database, password);
...
delete db;