2017-04-07 9 views
-2

メンバ関数 "print"を使用してベクトル "colors"を出力したいと思います。C++クラス内のベクトルを宣言して初期化する方法

/* Inside .h file */ 
class Color 
{ 
public: 
    void print(); 

private: 
    std::vector<std::string> colors; = {"red", "green", "blue"}; 
}; 

/* Inside .cpp file */ 

void Color::print() 
{ 
    cout << colors << endl; 
} 

しかし、私はというエラーメッセージが出ます:

Implicit instantiation of undefined template. 

ベクトルの宣言と初期化時に "色" クラス本体

、警告の内側:

In class initialization of non-static data member is a C++11 extension. 
+3

はあなたの 'の#include 'をしましたか?また、ヘッダーファイルで 'colors'と' = 'の間のセミコロンを取り除く必要があります。 – hlt

+0

そして、C++ 11対応コンパイラ。 –

+1

コンパイラのフラグにC++ 14またはC++ 11を有効にするだけです。しかし、 'std :: vector'に' << 'のオーバーロードがないので、' std :: cout << colors'にはまだ問題があります。 – Quentin

答えて

0

をあなたには多くの問題がありました:

  1. 一度だけ書いてstd::を書き留めておきます。
  2. 構文エラー:std::vector<std::string> colors; = {"red", "green", "blue"};

              ^
    
  3. あなたはすべての項目を取得するためにベクトルを反復処理しなければなりません。

これは動作し、あなたが望むものを表示するコードです:

#include <string> 
#include <iostream> 
#include <vector> 

/* Inside .h file */ 
class Color 
{ 
public: 
    void print(); 

private: 
    std::vector<std::string> colors = {"red", "green", "blue"}; 
}; 

/* Inside .cpp file */ 

void Color::print() 
{ 
    for (const auto & item : colors) 
    { 
     std::cout << item << std::endl; 
    } 
} 

int main() 
{ 
    Color myColor; 

    myColor.print(); 
} 

Live

関連する問題