我试图围绕连接指针编写一个简单的包装器,该包装器在销毁包装器时将其返回到池中,但是它不会编译,因为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/