无效使用不完整的类型"PGconn {aka struct pg_conn}"

invalid use of incomplete type 'PGconn {aka struct pg_conn}'

本文关键字:struct aka pg conn PGconn 用不完 类型 无效      更新时间:2023-10-16

>我有两个类,主类和一个连接类,如下所示:

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

康恩·

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

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

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

错误:前向声明"PGconn {aka struct pg_conn}"

有什么帮助吗?

在你的conn.h中,你应该将getConnection定义为返回一个PGconn *,而不是PGconnPGconn 是一个不透明的类型(除了名称之外,你的代码不应该知道任何关于它的信息),所以你不能返回它或按值使用它。

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

康恩·

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

康恩.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;
}

行:

PGconn getConnection();

由于PGConn是不完整的类型,因此不能定义按值返回它的函数,只能定义指向它的指针。