繁体   English   中英

C++ 中的模板类和函数

[英]Template Classes and Functions in C++

我有一个让我困惑的问题。 我知道什么是模板和它的目的,但我在使用上有一些空白点。

我有一个模板 class 像这样:

template <class elemType>
class SSorting {
public:

int seqSearch(const elemType list[], int length, const elemType& item);
};

当我对 class function seqSearch 的成员进行编码时,我需要声明为:

template <class elemType>
int SSorting <elemType> :: seqSearch(const elemType list[], int length, const elemType& item){
    *statements*
}

此时一切正常。 template says this is a function that inside a template class and int in front of the function means that the function will return an integer value, but the part that I don't understand is why we have to write SSorting <elemType>:: seqSearch而不是SSorting:: seqSearch 我已经说过这是模板 class 和返回类型的成员,为什么我们需要再次说<elemType>

您应该记得类/函数模板意味着对于每个具有不同模板类型的实例化,编译器会写下代码的另一个副本,将elemType替换为相关类型。 意思是,如果您在代码中同时使用SSorting<double>SSorting<int> ,您将获得两种完全不同的类型,具有不同的名称。

因此, class 的名称不是SSorting ,而是SSorting<elemType>

模板 class 不是“真正的” class,它是模板代码。 在您使用它之前它不存在。 当您不在定义部分写“elemType”部分时,您只是在定义“真实”class 的成员 function。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM