【问题标题】:Create object of template inner class创建模板内部类的对象
【发布时间】:2014-06-11 18:45:14
【问题描述】:

我有带有内部类的模板类

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;

如何创建内部类对象?

【问题讨论】:

标签: c++ class templates nested


【解决方案1】:

我在http://www.compileonline.com/compile_cpp11_online.php上试过这个

它按预期工作。对于这个狭窄的示例,您不需要为 Nested 定义析构函数,因为没有创建 Nested 实例。

#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;
}

【讨论】:

    【解决方案2】:

    你必须为内部类指定一个类型

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

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

    virtual ~Nested() {}
    

    【讨论】:

    • 当我这样做时,我得到编译错误 undefined reference to `Nested::~Nested()'
    • @user3574580:尝试向析构函数添加一些代码:virtual ~Nested() {}。
    猜你喜欢
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2019-05-05
    • 1970-01-01
    相关资源
    最近更新 更多