在C++中使用类型进行对象实例化。

huangapple go评论63阅读模式
英文:

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&lt;std::size_t&gt; 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&lt;std::size_t &gt; g;,您正在使用一个类模板实例化,其中size_t是类型参数。

您也可以使用Graph&lt;int &gt; g等等。

另外:

当编译器遇到模板方法定义时,它仅执行语法检查,但实际上不会编译模板。

让我们编写模板:

template&lt;typename T&gt;
class MyClass
{
    T memberVar{};
};

只有当编译器遇到模板的实例化,比如MyClass&lt;int&gt; 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&lt;std::size_t &gt; g; you are using one of the class template instantiation which has size_t as a type parameter.

You can use Graph&lt;int &gt; 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&lt;typename T&gt;
class MyClass
{
    T memberVar{};
};

Only when the compiler encounters an instantiation of the template, such as MyClass&lt;int&gt; 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.

huangapple
  • 本文由 发表于 2020年1月6日 20:06:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定