2017-09-20 9 views
-1

私は、このコード片の構文にconst K&k = K()はこのコンストラクタ関数で何を意味しますか?

を理解する難しさを持っています "K & K = K()、constのV & V = V()constは" の目的は何ですか?

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のユーザーが望む任意のデータ型を指定できますありがとうございます。

kおよびvは、Entryコンストラクタの入力パラメータです。それらはconst参照によって渡されており、デフォルト値が指定されています。K()はデフォルトでのtempオブジェクトを作成し、V()はデフォルトのVのtempオブジェクトを作成します。 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

OPがあなたがそれを行うことができないと思うので、構文 'K()'と 'V()'が何を意味するのかを話すのは害ではないかもしれません。 – templatetypedef

関連する問題