2016-04-14 5 views
-1

私はC++を初めて使用しています。私は最近、別のファイルでクラスを使用する小さなプログラムを作っていました。また、setterとgetter(set & get)関数を使用して変数に値を代入したいとします。コンパイラは私がプログラムを実行すると私に奇妙なエラーを与えます。 'string'は型を指定しないと言います。ここでは、コードです:'string'はタイプを指定しません - C++エラー

MyClass.h

#ifndef MYCLASS_H // #ifndef means if not defined 
#define MYCLASS_H // then define it 
#include <string> 

class MyClass 
{ 

public: 

    // this is the constructor function prototype 
    MyClass(); 

    void setModuleName(string &); 
    string getModuleName(); 


private: 
    string moduleName; 

}; 

#endif 

MyClass.cppファイル

#include "MyClass.h" 
#include <iostream> 
#include <string> 

using namespace std; 

MyClass::MyClass() 
{ 
    cout << "This line will print automatically because it is a constructor." << endl; 
} 

void MyClass::setModuleName(string &name) { 
moduleName= name; 
} 

string MyClass::getModuleName() { 
return moduleName; 
} 

main.cppにファイル

#include "MyClass.h" 
#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    MyClass obj; // obj is the object of the class MyClass 

    obj.setModuleName("Module Name is C++"); 
    cout << obj.getModuleName(); 
    return 0; 
} 
+0

'std :: string moduleName; – SergeyA

+0

私はそれを取得しませんでした。どのファイルを変更する必要がありますか?ステップごとに説明することができます。 –

+0

私と他の多くの人は、ヘッダーに 'using namespace std;'を追加することでこれを修正しようとすることを強くお勧めします。それは常に痛みにつながるわけではありませんが、それはあなたが抱く可能性が高いよりも多くの悲しみを引き起こします。その他の情報:http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice – user4581301

答えて

5

明示的std::名前空間スコープを使用する必要がありますヘッダファイルに:

あなたの .cppファイルで
class MyClass {  
public: 

    // this is the constructor function prototype 
    MyClass(); 

    void setModuleName(std::string &); // << Should be a const reference parameter 
        // ^^^^^ 
    std::string getModuleName(); 
// ^^^^^  

private: 
    std::string moduleName; 
// ^^^^^  
}; 

あなたはまた、のように明示的にstd::スコープを使用して、より良いまだ

using std::string; 

かでなければなりません

using namespace std; 
ひどくOKです

、より良いを持っていますヘッダー

+0

さらに、 '.cpp 'では' '使用していません。 'std :: string'はうまくいきます。 – SergeyA

+0

@SergeyAあいまいであれば、言及されているように大丈夫です。 –

+0

この文脈では、「大雑把に」とはどういう意味ですか? *全体*? – SergeyA

関連する問題