2017-10-18 15 views
4

私はプログラミングの新人です。私はvectorをC++で学んでいます。私はstring s = 42;がエラーを引き起こすが、文字列とベクトルの要素の違い<string>

vector<string>vec(3); 
vec[0] = 42; 

がない理由について興味があります。ありがとうございました!

答えて

9

std::vectorはそれとは何の関係もありません、std::vectorであなたのサンプルは

std::string s; 
s = 42; // assignation: s.operator =(42) 

std::string::operator=(char)はコンストラクタ撮影のに対し、存在するものと異なる

std::string s; 
s = 42; 

しかし

std::string s = 42; // Constructor: "equivalent" to std::string s = std::string(42) 

に似ていていますcharはありません。

+1

とint型は、「暗黙的に変換」になりCHAR – Steve

+3

@Steve正しい用語に暗黙的にキャスト可能です:私たちは、次のようにこれを確認することができます。 –

6

std::vectorは赤いニシンです。あなたは、単に次のことをしようとすると、それはまた、罰金コンパイルします:

あなたが実際に文字列を単一の文字を割り当て std::string::operator=(char)を使用しているやっている
#include <string> 
int main() 
{ 
    std::string str; 
    str = 42; 
} 

42は暗黙的にcharに変換可能です。 asciiテーブルによれば、値42は'*'文字で表されます。キャストは常に明示されている、

#include <iostream> 
#include <string> 
int main() 
{ 
    std::string str; 
    str = 42; 
    std::cout << str; // Prints * 
} 
関連する問題