「C++入門」コンストラクタのサンプル
書式
クラス名::コンストラクタ名()
使用例
#include <string>
#include <iostream>
using namespace std;
class TestA
{
private:
//メンバ変数名
string name;
public:
//コンストラクタ
TestA();
};
TestA::TestA()
{
cout << "123456 コンストラクタです\n";
}
//クラスを使用
int main() {
TestA ta;
return 0;
}
#include <string>
#include <iostream>
using namespace std;
class TestA
{
private:
//メンバ変数名
string name;
public:
//コンストラクタ
TestA();
};
TestA::TestA()
{
cout << "123456 コンストラクタです\n";
}
//クラスを使用
int main() {
TestA ta;
return 0;
}
#include <string> #include <iostream> using namespace std; class TestA { private: //メンバ変数名 string name; public: //コンストラクタ TestA(); }; TestA::TestA() { cout << "123456 コンストラクタです\n"; } //クラスを使用 int main() { TestA ta; return 0; }
実行結果
123456 コンストラクタです