2017-11-18 6 views
-4

は、次のヘッダーファイルを++ C++ではなぜint変数はクラスのprivateデータメンバとして宣言できますが、string変数では宣言できませんか? Cで

#ifndef SAMPLE_H_ 
#define SAMPLE_H_ 

class Sample { 
    private: 
     int number; 
}; 

#endif 

しかし、次のヘッダーファイル

合法で違法である

#ifndef 
#define 

class Sample { 
    private: 
     string name; 
}; 

#endif 

なぜそれがそのようなものですか?私の場合は

I次のヘッダファイルがあります。

Alphabet.h

#include <string> 

#ifndef   ALPHABET_H_ 
#define   ALPHABET_H_ 


class Rhyme { 

private: 
    string a; 

public: 

    Rhyme(); 

}; 

#endif 

Alphabet.cpp

#include <iostream> 
#include "Alphabet.h" 

using namespace std; 

Rhyme::Rhyme() { 

    a = "A for Apple"; 
} 

MAIN.CPP

#include <iostream> 
#include "Alphabet.h" 

using namespace std; 

int main() { 

    Rhyme rhyme; 
    return 0; 
} 

Linuxのターミナルコマンドを実行します。この後

g++ *.cpp 
./a.out 

私は、次のエラーを取得しています:

エラー:

In file included from Alphabets.cpp:2:0: 
Alphabet.h:10:2: error: ‘string’ does not name a type 
    string a; 
^
Alphabets.cpp: In constructor ‘Rhyme::Rhyme()’: 
Alphabets.cpp:8:2: error: ‘a’ was not declared in this scope 
    a = "A for Apple"; 
^
In file included from Main.cpp:2:0: 
Alphabet.h:10:2: error: ‘string’ does not name a type 
    string a; 

私はprivateとしてheader filestring member variableを宣言しようとしています、 constructor

を使用して別のファイルから初期化します
+6

は、両方が有効です。ヘッダファイルに '#include 'がありませんので、エラーが発生していると思います。 – Ivan

+3

私たちができることがあればどんなエラー(もしあれば)もわからなくても推測できます。 [良い質問をする方法を読む](http://stackoverflow.com/help/how-to-ask)を読んで、[最小限の完全で検証可能な例](http:// stackoverflow。 com/help/mcve)。 –

+1

あなたが表示するコードスニペットは実際には無効です。 '#ifndef'と' #define' *何*? –

答えて

4

を書く必要は組み込みのキーワードで、どこかのコードで有効なタイプです。 stringは、<string>ヘッダーに定義されているstd名前空間のクラスで、最初にヘッダーを含める場合にのみ使用できます。

ヘッダーファイル(名前空間汚染)にusing namespace指示文を使用しないでください。したがって、std::stringと記述する必要があります。

また、あなたのためのヘッダ(例えばSAMPLE_H)のファイル名を使用してガードを含める:

#ifndef SAMPLE_H 
#define SAMPLE_H 

#include <string> 

class Sample { 
    private: 
     std::string name; 
}; 

#endif 
1

std::stringは、ヘッダー<string>で宣言されている標準のユーザー定義クラスです。だから、ヘッダ

#include <string> 

と標準名前空間stdに配置さを含める必要があります。

ですから、少なくともC++、int

class Sample { 
    private: 
     std::string name; 
}; 
関連する問題