C++ 结构没有在c++;

C++ 结构没有在c++;,c++,struct,compilation,C++,Struct,Compilation,当返回类型为结构时,我遇到问题 Example.h class Example { private: typedef struct connection_header { string url; string method; }; static connection_header get_connection_header(); }; Example.cpp connection_header Example::get_connect

当返回类型为结构时,我遇到问题

Example.h

class Example {
private:
    typedef struct connection_header {
        string url;
        string method;
    };

    static connection_header get_connection_header();
};

Example.cpp
connection_header Example::get_connection_header() {
    return NULL;
}
我得到的
'connection\u header'没有命名类型


我可以知道为什么会出现此错误吗

您使用的是
typedef
,但没有给出类型名称。只需放下
typedef
,此处不需要它:

struct connection_header {
    string url;
    string method;
};
接下来,
connection\u header
Example
类中声明,因此当它是返回类型时,您需要在实现中完全限定它的名称:

Example::connection_header Example::get_connection_header()

首先,在C++(而不是C)中,每个<代码>结构> <代码>或<代码>类< /C> >命名一个类型。因此,如果您声明一个

struct connection\u header
,您还将得到一个
connection\u header
类型,以便以后可以声明
connection\u header var
一些变量

那么,<代码> TyPufF C和C++中都需要一个类型和一个名称。例如:

 typedef long my_number_type;
my\u number\u type
声明为
long


正如其他人所指出的,删除
typedef

cpp
文件中尝试下面的代码,在
连接头之前添加
示例::

Example::connection_header Example::get_connection_header() {
    return NULL;
}
connection\u header
是在
Example
中定义的,因此您应该给出它的定义范围


也可以忽略C++中的关键字<代码> TyPulfF。您可以省略它

除了其他人的答案之外,我建议您不要嵌套数据结构的定义。在
示例
上方为
连接头
创建单独的外部
结构

Example.h

struct ConnectionHeader {
    string url;
    string method;
};

class Example {
private:
    ConnectionHeader connection_header;
    static ConnectionHeader get_connection_header();
};

这更易于调试,提供更好的可重用性,并且更容易预测
auto
的结果。否则,只需使
url
method
成为
Example
的成员,并让
get\u connection\u header()
将这些值更新到位,返回
void

还有另一个典型的问题,即使用了尚未声明的类型。如果你使用类型,在使用它们之前声明它们。

我不认为这是C++中的好建议,你会希望Struts像类一样运行,而不需要在PASC上的对象名称前面键入<代码> Stutt关键字。@ Lundin并不是到处都是。这是结构的实际声明。但是当你使用结构时,你必须键入连接头,因为连接头不是一个类型,而是一个结构标记。@Lundin,不,你错了。现在,结构只是一个具有不同默认可访问性规则的类。@Lundin在
中对
结构
使用C样式声明是不向后兼容的。您的下一个错误可能是
没有从int到connection\u头的转换。什么类型的
NULL
?@PeterWood感谢java给我的通知,所以我们通常可以这样做。我修复了和可能重复的问题