私は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;
}
'std :: string moduleName; – SergeyA
私はそれを取得しませんでした。どのファイルを変更する必要がありますか?ステップごとに説明することができます。 –
私と他の多くの人は、ヘッダーに 'using namespace std;'を追加することでこれを修正しようとすることを強くお勧めします。それは常に痛みにつながるわけではありませんが、それはあなたが抱く可能性が高いよりも多くの悲しみを引き起こします。その他の情報:http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice – user4581301