c++ - 无法将 namespace_something::some_class 转换为 some_class

标签 c++

两个类都是一样的,例子:

///////////////server.h//////////////
#ifndef SERVER_H
#define SERVER_H

#ifdef WIN32
        #ifndef _WIN32_WINNT
                #define _WIN32_WINNT 0x0501
        #endif
#endif
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <map>

#include "auxiliar.h"

class Client;

namespace Irc
{
        typedef boost::shared_ptr<Client> ClientPtr;
        typedef std::map<SocketPtr, ClientPtr> ClientsMap;

        class Server
        {
                public:
                        Server();
                        ~Server();

                        void start();

                        void startAccept();

                        ClientsMap::const_iterator begin() { return m_clients.begin(); }
                        ClientsMap::const_iterator end() { return m_clients.end(); }

                private:
                        ClientsMap m_clients;
                        boost::asio::io_service service;
                        boost::asio::ip::tcp::acceptor* m_acceptor;
        };
} //namespace Irc
#endif
/////////////server.cpp////////////////
#include "server.h"
#include "defines.h"
#include "client.h"

Irc::Server::Server()
{
        service.run();
}

Irc::Server::~Server()
{
        m_clients.clear();
}

void Irc::Server::start()
{
        m_acceptor = new boost::asio::ip::tcp::acceptor(service, boost::asio::ip::tcp::endpoint(
                boost::asio::ip::tcp::v4(), SERVER_PORT));
}

void Irc::Server::startAccept()
{
        SocketPtr s(new boost::asio::ip::tcp::socket(service));
        m_acceptor->accept(*s);
        Client *client = new Client(s);
        client->setIoService(&service);
        ClientPtr ptr(client);
        m_clients.insert(std::make_pair(s, ptr));
}

这会产生编译错误:

g++.exe -c src/server.cpp -o src/server.o -I"D:/Dev-Cpp/include" -g -ggdb -I"include" -fexpensive-optimizations -O1 D:/Dev-Cpp/include/boost/smart_ptr/shared_ptr.hpp: In constructor boost::shared_ptr< <template-parameter-1-1> >::shared_ptr(Y*) [with Y = Irc::Client, T = Client]': src/server.cpp:27: instantiated from here D:/Dev-Cpp/include/boost/smart_ptr/shared_ptr.hpp:179: error: cannot convertIrc::Client*' to `Client*' in initialization

最佳答案

您应该将前向声明 class Client inside 命名空间 Irc

namespace Irc {
   class Client;  // put it here.
   ...

否则,ClientPtr 的 typedef 将引用没有命名空间的 Client(因为它是找到的最接近的 Client 声明),而不是 Irc: :Client 你想要的。

   typedef boost::shared_ptr<Client> ClientPtr;

关于c++ - 无法将 namespace_something::some_class 转换为 some_class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4147149/

相关文章:

c++ - 如何在 C 中实现 RFC 3393(Ipdv 数据包延迟变化)?

c++ - GNU 的 nana 库死了吗?是否有后继者在使用?

c++ - Qt C++ 未处理的异常堆栈跟踪

用于创建字符串数组的 C++ 宏

c++ - Dropbox Djinni 可以与 C++98 一起使用吗

c++ - 如何使用指针遍历结构数组中的数组

c++ - shared_ptr : horrible speed

c++ - 使用 STL 类而不包含其适当的 header

c++ - gcc 和 clang 上奇怪的嵌套类部分特化结果

c++ - 将 uint64_t 转换为 unsigned char serialized[8]