英文:
Object instantiation in C++ with type
问题
为什么在以下代码行中我们要在Graph之后写size_t呢?
Graph<std::size_t> g;
Graph是一个类名,g是一个对象。size_t在这里的作用是什么?为什么我们要写它?
如果问题太基础,我非常抱歉。但我找不到解释,到目前为止,当我想创建一个类的对象时,我会写成这样:
class_name object;
就像这样:
Graph g;
英文:
May someone tell me please why we do write size_t after Graph in the following line?
Graph<std::size_t> g;
Graph is a class name and g is an object. What does size_t do there? Why should we write that?
I am so sorry if the question is too basic. But I could not find explanation on this and so far when I've wanted to create an object of class I have written:
class_name object;
like:
Graph g;
答案1
得分: 2
因为Graph是一个类模板而不是普通类。
类模板定义了一个类,其中某些变量的类型、方法的返回类型和/或方法的参数被指定为参数。
因此,通过使用Graph<std::size_t > g;,您正在使用一个类模板实例化,其中size_t是类型参数。
您也可以使用Graph<int > g等等。
另外:
当编译器遇到模板方法定义时,它仅执行语法检查,但实际上不会编译模板。
让我们编写模板:
template<typename T>
class MyClass
{
    T memberVar{};
};
只有当编译器遇到模板的实例化,比如MyClass<int> myObj,它才会通过将类模板定义中的每个T替换为int等等来为int版本的MyClass模板编写代码。
英文:
Because Graph is a class template not an ordinary class.
Class templates define a class where the types of some of the variables, return types of methods, and/or parameters to the methods are specified as parameters.
Hence by using Graph<std::size_t > g; you are using one of the class template instantiation which has size_t as a type parameter.
You can use Graph<int > g too and so on.
An addition:
When the compiler encounters template method definitions, it performs syntax
checking ony, but doesn’t actually compile the templates.
Let us write the template
template<typename T>
class MyClass
{
    T memberVar{};
};
Only when the compiler encounters an instantiation of the template, such as MyClass<int> myObj, it writes code for an int version of the MYClass template by replacing each T in the class template definition with int and so on.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论