クラスの継承
特徴
* C++にはインターフェースクラスはない => インターフェースクラスを表現したい場合、抽象クラスを使う * C++には多重継承が可能
構文
class クラス名 : public 基底クラス名
{
追加の宣言
}
サンプル
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;
}
Student.h
#ifndef Student_h
#define Student_h
#include "stdafx.h"
#include "Person.h"
class Student : public Person
{
public:
void showStudentId();
};
#endif
Student.cpp
#include "stdafx.h"
#include "Student.h"
using namespace std;
void Student::showStudentId()
{
cout << "Student Id : " << this->id << endl;
}
SampleCpp.cpp
#include "stdafx.h"
#include "Person.h"
#include "Student.h"
using namespace std;
int main(array<System::String ^> ^args)
{
Student* s = new Student();
s->id = 23;
s->showStudentId();
return 0;
}
参考文献
http://www.atmarkit.co.jp/fdotnet/bookpreview/bunpouvcpp_1003/bunpouvcpp_1003_01.htmlhttp://blog.livedoor.jp/cppcli/archives/414477.html