简体   繁体   English

C ++类Typedef Struct未命名类型

[英]C++ Class Typedef Struct does not name a type

I'm trying to make use of typedef structs inside of my C++ program. 我正在尝试在我的C ++程序中使用typedef结构。 I started writing the following code until I received an error when trying to add a method to my class that returns a template typedef struct pointer. 我开始编写以下代码,直到我在尝试向我的类添加一个返回模板typedef结构指针的方法时收到错误。

StructSource.h StructSource.h

template <typename T>
class StructSource {
public:
    struct TestStruct{
        T value;
    };
};

User.h User.h

#include "StructSource.h"

class User {
    public:
        typedef StructSource<int>::TestStruct IntStruct;

        IntStruct *getIntStruct();

};

User.cpp User.cpp

#include "User.h"

IntStruct *User::getIntStruct() {
    return 0;
}

This gives the following error when compiling with GCC. 在使用GCC进行编译时,会出现以下错误。

User.cpp:3:1: error: 'IntStruct' does not name a type User.cpp:3:1:错误:'IntStruct'没有命名类型

I'm at a loss to explain why this is the case. 我无法解释为什么会这样。 What type information am I missing? 我错过了什么类型的信息?

"User" is also a "namespace" (scope, actually, as most commenters point out - "namespace" was for a quick answer) here, so you have to use “用户”也是一个“命名空间”(范围,实际上,正如大多数评论者指出的那样 - “命名空间”用于快速回答),所以你必须使用

User::IntStruct *User::getIntStruct() {
    return 0;
}

You need: 你需要:

User::IntStruct *User::getIntStruct() { ... }

IntStruct is defined inside the User scope, but the return value of the function is not in scope. IntStruct在User范围内定义,但函数的返回值不在范围内。 there is a discussion of these scoping issues here . 有这些范围的问题的讨论在这里

Since IntStruct was defined within the class, you must use the class name to reference it, except within the class code where it is part of the default name search path. 由于IntStruct是在类中定义的,因此必须使用类名来引用它,除非在类代码中它是默认名称搜索路径的一部分。

User::IntStruct *User::getIntStruct() {

This is not the same as a namespace, even though the syntax is identical. 这是一样的命名空间,即使语法是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM