结构转发声明失败编译 [英] struct forward declaration fails compile

查看:143
本文介绍了结构转发声明失败编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,但编译器说sender_wrapper是未定义的,即使我转发声明它。我可以不做一个结构的向前声明吗? (用VS2003编译)

I have the following code, but the compiler says sender_wrapper is undefined, even though I forward declared it. Can I not do a forward declare of a struct? (compiled with VS2003)

struct send_wrapper;

struct IPSend
{
    IPSend::IPSend(const send_wrapper& sender) : _sender(sender) {}

    void IPSend::operator()(const std::string& msg)
    {           
        if (!msg.empty())
            _sender.send(msg);
    }

    send_wrapper _sender; //error C2079: 'IPSend::_sender' uses undefined struct 'send_wrapper'

};

struct send_wrapper 
{
std::auto_ptr<tcp_server> server;

};


推荐答案

转发类型声明只能用于解析声明

Forward declarations of types can only be used to resolve declarations involving pointers and references to that type.

在完全定义类型之前,编译器不知道任何关于类型;例如它有什么成员,或者它有多大。因此,您不能将其用作结构的按值成员,因为编译器不会知道它有多大,或者它的构造函数和析构函数是否公开。另一方面,你可以自由地做类似 send_wrapper * _p_sender; 的操作,因为指向结构体的指针总是相同的大小。但您仍然无法访问其成员函数等。

Before the type has been fully defined, the compiler does not know anything about the type; e.g. what members it has, or how big it is. Therefore, you cannot use it as a by-value member of your struct, because the compiler wouldn't know how big to make it, or whether its constructors and destructor are public. On the other hand, you are free to do something like send_wrapper *_p_sender;, because pointers to structs are always the same size. But you still wouldn't be able to access its member functions, etc.

这篇关于结构转发声明失败编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆