2014-04-25 131 views
0

我有一個內部類模板類創建模板內部類對象

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()' 

和未來posiblities:

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; 

如何創建內部類對象?

+0

可能重複http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the -header-file) – 0x499602D2

回答

0

你必須指定內部類

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

類型和一些代碼添加到您的析構函數

virtual ~Nested() {} 
+0

當我這樣做,我得到編譯錯誤未定義引用'嵌套 ::〜嵌套()' – anycmon

+0

@ user3574580:嘗試添加一些代碼到你的析構函數:virtual〜Nested(){}。 –

0

我想這對http://www.compileonline.com/compile_cpp11_online.php

它按預期工作。對於這個狹窄的例子,因爲沒有創建嵌套的<>實例,所以不需要定義嵌套的析構函數>。

#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; 
} 
的[爲什麼模板只能在頭文件中實現?(