gpt4 book ai didi

c++ - 当两个类相互引用时编译 C++

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:54:44 24 4
gpt4 key购买 nike

我正在尝试围绕连接指针编写一个简单的包装器,当包装器被销毁时,它将把它返回到池中,但它不会编译,因为 ConnectionPool 和 AutoConn 需要彼此声明。

我尝试使用向前减速但没有用。我该如何解决这个问题? (使用 g++)

class Connection {};

class ConnectionPool
{
Connection *m_c;
public:
AutoConn getConn()
{
return AutoConn(this, m_c); // by value
}

void releaseConnection(Connection *c)
{
}
};

class AutoConn
{
ConnectionPool* m_pool;
Connection *m_connection;
public:
AutoConn(ConnectionPool* pool, Connection *c) : m_pool(pool), m_connection(c) {}
~AutoConn()
{
m_pool->releaseConnection(m_connection);
}
};

最佳答案

前向声明和声明与循环依赖成员定义分离的组合有效。例如:

class Connection {};
class ConnectionPool ;

class AutoConn
{

ConnectionPool* m_pool;
Connection *m_connection;
public:
AutoConn(ConnectionPool* pool, Connection *c) : m_pool(pool), m_connection(c) {}
~AutoConn() ; // Not defined here because it accesses unknown members of class Connection
} ;

class ConnectionPool
{
Connection *m_c;
public:
AutoConn getConn()
{
return AutoConn(this, m_c); // by value
}

void releaseConnection(Connection *c)
{
}
};

// Definition of destructor with class Connection member dependencies.
AutoConn::~AutoConn()
{
m_pool->releaseConnection(m_connection);
}

关于c++ - 当两个类相互引用时编译 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2447310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com