2017-09-20 37 views
-1

我有困难理解这个代码片段在这个构造函数中,const K&k = K()是什么意思?

是什么的目的的语法 “常量ķ& K = K(),常量V & V = V()”?

template<typename K, typename V> 
class Entry{ 

    public: 
     typedef K Key; 
     typedef V Value; 
    public: 
     Entry(const K& k = K(), const V& v = V()) : _key(k), _value(v) {} 

    .... 
     .... 
      .... 
    private: 
     K _key; 
     V _value; 
}; 

谢谢

+7

你知道一个参考是什么?你知道默认的功能参数是什么吗?如果没有,你应该得到一个[很好的C++书](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver

+0

它是C++模板语法。 K和V可以是任何类型或结构。 – jesuisgenial

+0

这是将K和V的实例注入类的私有属性 – jesuisgenial

回答

1

KV是模板参数,它们可以是任何数据类型的Entry用户希望。

kv是构造函数Entry的输入参数。它们通过const引用传入,并且它们具有指定的默认值,其中K()默认构造一个类型为K的临时对象,而V()默认构造一个类型为V的临时对象。如果用户在创建Entry对象实例时未提供显式输入值,则会改为使用默认值。

例如:

Entry<int, int> e1(1, 2); 
// K = int, k = 1 
// V = int, v = 2 

Entry<int, int> e2(1); 
// aka Entry<int, int> e2(1, int()) 
// K = int, k = 1 
// V = int, v = 0 

Entry<int, int> e3; 
// aka Entry<int, int> e3(int(), int()) 
// K = int, k = 0 
// V = int, v = 0 

Entry<std::string, std::string> e4("key", "value"); 
// K = std::string, k = "key" 
// V = std::string, v = "value" 

Entry<std::string, std::string> e5("key"); 
// aka Entry<std::string, std::string> e4("key", std::string()) 
// K = std::string, k = "key" 
// V = std::string, v = "" 

Entry<std::string, std::string> e6; 
// aka Entry<std::string, std::string> e4(std::string(), std::string()) 
// K = std::string, k = "" 
// V = std::string, v = "" 
+1

说到'K()'和'V()'的语法意思可能没有什么不好,因为我认为OP不知道你可以这样做。 – templatetypedef

相关问题