无效使用不完整类型“PGconn {aka struct pg_conn}”

5 c c++ oop

我有两个类,主类和连接类:

康涅狄格州.cpp:

#include "conn.h"
#include <postgresql/libpq-fe.h>

Conn::getConnection()
{
        connStr = "dbname=test user=postgres password=Home hostaddr=127.0.0.1 port=5432";
        PGconn* conn;
        conn = PQconnectdb(connStr);
        if(PQstatus(conn) != CONNECTION_OK)
              {
                cout << "Connection Failed.";
                PQfinish(conn);
              }
        else
              {
                cout << "Connection Successful.";
              }
        return conn;

}
Run Code Online (Sandbox Code Playgroud)

康涅狄格州

#ifndef CONN_H
#define CONN_H
#include <postgresql/libpq-fe.h>
class Conn
{
public:
    const char *connStr;
    Conn();
    PGconn getConnection();
    void closeConn(PGconn *);
};
Run Code Online (Sandbox Code Playgroud)

主要.cpp

#include <iostream>
#include <postgresql/libpq-fe.h>
#include "conn.h"

using namespace std;

int main()
{
    PGconn *connection = NULL;
    Conn *connObj;
    connection = connObj->getConnection();

return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:无效使用不完整类型“PGconn {aka struct pg_conn}”

错误:“PGconn {aka struct pg_conn}”的前向声明

有什么帮助吗?

bil*_*llz 1

在您的 conn.cpp 中,conn::getConnection()没有返回类型。从你的代码中,我猜你需要返回一个指向 PGconn 的指针:

康涅狄格州

class Conn
{
public:
    const char *connStr;
    Conn();
    PGconn* getConnection();
          ^^ return pointer instead of return by value
    void closeConn(PGconn *);
};
Run Code Online (Sandbox Code Playgroud)

康涅狄格州.cpp

PGconn* Conn::getConnection()
^^^^^^ // return PGconn pointer
{
   connStr = "dbname=test user=postgres password=Home hostaddr=127.0.0.1 port=5432";

   PGconn* conn = NULL;
   conn = PQconnectdb(connStr);
   if(PQstatus(conn) != CONNECTION_OK)
   {
       cout << "Connection Failed.";
       PQfinish(conn);
   }
    else
    {
      cout << "Connection Successful.";
    }
    return conn;
}
Run Code Online (Sandbox Code Playgroud)