クラスの作成方法
クラスを定義するキーワードには、以下の2通りある。
[1] class
[2] struct
※ classを使って定義したクラスのメンバは、既定でprivateで、
structを使って定義したクラスのメンバは、public。
構文
class クラス名
{
アクセス修飾子:
型 変数名;
関数 関数名(引数)
{
処理
}
};
* アクセス修飾子:public、protected、private
サンプル
Person.h
#ifndef Person_h
#define Person_h
#include "stdafx.h"
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
using namespace System;
class Person
{
public:
int id;
string name;
char sex;
int age;
Person();
~Person();
void display();
};
#endif
Person.cpp
* thisポインタ(ex. this->id)については、以下を参照のことhttp://wisdom.sakura.ne.jp/programming/cpp/cpp15.html
#include "stdafx.h"
#include "Person.h"
#include <iostream>
using namespace std;
Person::Person()
{
cout << "コンストラクタ" << endl;
}
Person::~Person()
{
cout << "デストラクタ" << endl;
}
void Person::display()
{
stringstream ss;
ss << "Person : " << this->id << " " << this->name << " "
<< this->sex << " " << this->age;
cout << ss.str() << endl;
}
SampleCpp.cpp
#include "stdafx.h"
#include "Person.h"
using namespace std;
int main(array<System::String ^> ^args)
{
Person* person = new Person();
person->id = 1;
person->name = "Mike";
person->sex = 'M';
person->age = 27;
person->display();
delete person;
return 0;
}
参考文献
http://www.atmarkit.co.jp/fdotnet/bookpreview/bunpouvcpp_1001/bunpouvcpp_1001_02.htmlhttp://www.ogis-ri.co.jp/otc/hiroba/technical/CppDesignNote/