如何使用带有类的模板的结构 [英] How to have a Struct with template with a class

查看:24
本文介绍了如何使用带有类的模板的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码(只是一类测试):

With this code (just a class of test):

typedef unsigned short UInt16;

template<class T>
class CClass
{
public:
    SValue* getNewSValue(void);
private:
    typedef struct {
        T *mValue;
        T *next;
        T *previous;
        UInt16 index;
    } SValue;
};

template<typename T>
SValue* CClass<T>::getNewSValue(void)
{
    return new SValue;
}

我有以下错误:

错误 C2143:语法错误:缺失';''*'之前

error C2143: syntax error : missing ';' before '*'

错误 C4430:缺少类型说明符 -int 假设.注意:C++ 没有支持 default-int

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

是否可以在类中使用 Struct?如果我从类中声明结构体,模板将看不到模板 T.

Is it possible to use a Struct within a class? If I declare the struct out of the class the template doesn't see the template T.

推荐答案

$9.2/2- 关键是下面引用的 C++ Standard03

$9.2/2- The key is the below quote from the C++ Standard03

`在类说明符的结尾 } 处,类被认为是完全定义的对象类型 (3.9)(或完整类型).在类成员规范中,类在函数体、默认参数和构造函数构造函数初始化器(包括嵌套类中的此类内容)中被视为完整的.否则,它在自己的类成员规范中被认为是不完整的.

`A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments and constructor ctor-initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

不知道什么是UINT16,但以下应该可以工作

Don't know what is UINT16, but the following should work

template<class T> 
class CClass 
{ 
private: 
    typedef struct { 
        T *mValue; 
        T *next; 
        T *previous; 
        short int index;                      // Replacing with int for illustration only
    } SValue; 
public:
    SValue* getNewSValue(void); 
private: 
}; 

EDIT 3:*** 来这里是为了进行 BOLD 更改(无论如何我应该删除)

EDIT 3: The *** came there trying to make the change BOLD (which I should have deleted anyways)

template<class T> typename CClass<T>::SValue* CClass<T>::getNewSValue(void) 
{ 
    return new SValue; 
}

int main(){
    CClass<int> s;
    s.getNewSValue();
}

这篇关于如何使用带有类的模板的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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