创建模板内部类的对象

时间:2014-04-25 21:39:15

标签: c++ class templates nested

我有内部类的模板类

template<class param>
class Nested {
    param obj;
public:
    template<class X>
    class Inner {
        X obj;
    public:
        Inner(X obj) : obj(obj) {}
        X getObj() { return obj; }
    };
    Nested();
    Nested(param obj) : obj(obj) {}
    param getObj() { return obj; }
    virtual ~Nested();
};

我试试:

Nested<int>::Inner<int> inner(43);

但是我收到了编译错误:

C++/TemplateClass/Debug/../src/TemplateClass.cpp:20: undefined reference to `Nested<int>::~Nested()'
C++/TemplateClass/Debug/../src/TemplateClass.cpp:20: undefined reference to `Nested<int>::~Nested()'

和下一个可能性:

    Nested<int>::Inner inner(43);

../src/TemplateClass.cpp: In function ‘int main()’:
../src/TemplateClass.cpp:17:24: error: invalid use of template-name ‘Nested<int>::Inner’ without an argument list
  typename Nested<int>::Inner inner(43);
                        ^
../src/TemplateClass.cpp:17:35: error: invalid type in declaration before ‘(’ token
  typename Nested<int>::Inner inner(43);
                                   ^
../src/TemplateClass.cpp:18:42: error: request for member ‘getObj’ in ‘inner’, which is of non-class type ‘int’
  cout << "Inner param object: " << inner.getObj() << endl;

如何创建内部类对象?

2 个答案:

答案 0 :(得分:0)

您必须为内部类指定类型

Nested<int>::Inner<char> inner(43);

并向析构函数添加一些代码

virtual ~Nested() {}

答案 1 :(得分:0)

我在http://www.compileonline.com/compile_cpp11_online.php

上试过了

按预期工作。对于这个狭窄的例子,您不需要为嵌套的&lt;&gt;定义析构函数。因为嵌套&lt;&gt;实例未创建。

#include <iostream>

template<class param>
class Nested {
    param obj;
public:
    template<class X>
    class Inner {
        X obj;
    public:
        Inner(X obj) : obj(obj) {}
        X getObj() { return obj; }
    };
    Nested();
    Nested(param obj) : obj(obj) {}
    param getObj() { return obj; }
    virtual ~Nested();
};

int main()
{
    Nested<int>::Inner<int> temp(43);
    std::cout << temp.getObj() << std::endl;
    return 0;
}