2014-12-03 78 views
0

我无法完全理解这些模板如何在C++中工作,我有一个驱动程序代码,我正在尝试编写头文件。我可以得到这段代码进行编译,它应该输出'a'作为第一个字符,'d'作为第二个字符。如果有人能指出我在这个头文件中出错的地方,我会在第一个和第二个字符的输出中得到一个无法识别的字母。提前致谢。如何使用模板返回char值

头文件

template <class T> 
class Pair 
{ 
private: 
    T firstChar; 
    T secondChar; 
public: 
    Pair(const T& , const T&); 
    T getFirst(); 
    T getSecond(); 
}; 

template <class T> 
Pair<T>::Pair(const T&, const T&) 
{ 
    firstChar; 
    secondChar; 
} 

template <class T> 
T Pair<T>::getFirst () 
{ 
    return firstChar; 
} 

template <class T> 
T Pair<T>::getSecond () 
{ 
    return secondChar; 
} 

驱动程序文件

#include <iostream> 
#include "pair.h" 
using namespace std; 


int main() 
{ 
    Pair<char> letters('a', 'd'); 
    cout << "\nThe first letter is: " << letters.getFirst(); 
    cout << "\nThe second letter is: " << letters.getSecond(); 
    cout << endl; 
    system("Pause"); 
    return 0; 
} 

回答

2

你的构造函数没有做任何有用的事情。你想让它使用它的参数来初始化成员变量:

template <class T> 
Pair<T>::Pair(const T& first, const T& second) : 
    firstChar(first), 
    secondChar(second) 
{} 

如果启用编译器警告,它应该告诉你的陈述firstChar;secondChar;什么也不做。

1
template <class T> 
Pair<T>::Pair(const T&, const T&) 
{ 
    firstChar; 
    secondChar; 
} 

此构造没有做任何事情,它没有任何命名参数,也没有对会员属性,它为它们分配,也许你想用:

template <class T> 
Pair<T>::Pair(const T& first, const T& second) : firstChar(first), secondChar(second) 
{ 

}