抽象数据库的c++实现
Abstract database implementation in C++
我想创建抽象的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()函数看起来更紧凑。我只是试图隐藏连接细节的地方,如连接字符串。
在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;
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的