【问题标题】:What does the additional colon mean in a templated class. ClassName<T, SIZE>::ClassName:模板类中的附加冒号是什么意思。类名<T, SIZE>::类名:
【发布时间】:2013-06-16 12:49:30
【问题描述】:

这个函数定义中的附加“:”是什么意思?

template <class T, int SIZE> 
class Buffer
{
 public: 
    Buffer();
 private: 
    int _num_items; 
};

template <class T, int SIZE> 
Buffer<T, SIZE>::Buffer() :
    _num_items(0) //What does this line mean?? 
{
   //Some additional code for constructor goes here. 
}

我会搜索这个,但我不知道这种做法叫什么。我刚刚开始学习模板,并在模板类中遇到了这个。

【问题讨论】:

  • 搜索“构造函数初始化列表”

标签: c++ class templates constructor colon


【解决方案1】:

这就是初始化成员变量的方法(你应该这样做)

class Something
{
private:
  int aValue;
  AnotherThing *aPointer;

public:
  Something() 
   : aValue(5), aPointer(0)
  {
     printf(aValue); // prints 5
     if(aPointer == 0) // will be 0 here
       aPointer = new AnotherThing ();
  }
}

这是初始化列表 - 成员将使用给定值初始化。

【讨论】:

  • 感谢您的回答,请问这仅适用于模板类还是适用于任何类?
  • 任何类都可以这样初始化它的成员。在您的情况下,它是一个模板类,但此初始化列表适用于 C++ 中的所有类。只需谷歌c++ constructor initialization list
  • 谢谢。这个网站很棒。有些东西我什至不知道从哪里开始找到它。
  • 不客气。 stackoverflow 真的很震撼!如果您想接受答案,可以单击左侧的复选标记,这样用户就可以看到这个问题已经得到了答案 :)
  • 我在等待,因为我猜您必须等待 10 分钟才能选择答案。这让我走上了正轨。
猜你喜欢
  • 2020-08-15
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 2014-05-30
相关资源
最近更新 更多