コンストラクタ

Cプログラマのための C++入門 > 2.クラスの概念 >

コンストラクタ

C++


#include <stdio.h>
#include "Student.h"

void PrintStudent(Student x)
{
printf("%s\n", x.Name());
printf(" 英語 = %d\n", x.English());
printf(" 数学 = %d\n", x.Mathematics());
printf(" 平均 = %d\n", x.Average());
}

int main(int argc, char* argv[])
{
Student Shibata("柴田望洋", 100, 100);
Student Masuyan("増田真二", 80, 80);

PrintStudent(Shibata);
PrintStudent(Masuyan);

return 0;
}

Student.h

class Student
{
char name[20];
int eng;
int math;
int ave;
public:
Student(const char*, int, int);

void SetName(const char*);
void SetEng(const int en) {eng = en;}
void SetMath(const int mat) {math = mat;}
void CalcAve(void) {ave = (eng + math) / 2;}

char* Name(void) {return name;}
int English(void) {return eng;}
int Mathematics(void) {return math;}
int Average(void) {return ave;}
};

Student.cpp

#include <string.h>
#include "Student.h"

Student::Student(const char* n, int en, int mat)
{
strcpy(name, n);
eng = en;
math = mat;
CalcAve();
}

void Student::SetName(const char* n)
{
strcpy(name, n);
}

実行結果


R:\>lesson005\project1.exe
柴田望洋
英語 = 100
数学 = 100
平均 = 100
増田真二
英語 = 80
数学 = 80
平均 = 80

Delphi


program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils, Student;

procedure PrintStudent(x:TStudent);
begin
Writeln(Format('%s', [x.name]));
Writeln(Format(' 英語= %d', [x.English]));
Writeln(Format(' 数学= %d', [x.Mathematics]));
Writeln(Format(' 平均= %d', [x.Average]));
end;

procedure main();
var
Shibata: TStudent;
Masuyan: TStudent;
begin
Shibata := TStudent.Create('柴田望洋', 100, 100);
Masuyan := TStudent.Create('増田真二', 80, 80);

PrintStudent(Shibata);
PrintStudent(Masuyan);

Shibata.Free;
Masuyan.Free;
end;

begin
main;
end.

Student.pas

unit Student;

interface
type
TStudent = class
private
nam: String;
eng: Integer;
math: Integer;
ave: Integer;
public
constructor Create(n:String; en:Integer; mat:Integer);
procedure SetName(n:String);
procedure SetEng(en:Integer);
procedure SetMath(mat:Integer);
procedure CalcAve();

function name():String;
function English():Integer;
function Mathematics():Integer;
function Average():Integer;
end;


implementation
constructor TStudent.Create(n:String; en:Integer; mat:Integer);
begin
nam := n;
eng := en;
math := mat;
CalcAve;
end;

procedure TStudent.SetName(n:String);
begin
nam := n;
end;

procedure TStudent.SetEng(en:Integer);
begin
eng := en;
end;

procedure TStudent.SetMath(mat:Integer);
begin
math := mat;
end;

procedure TStudent.CalcAve();
begin
ave := (eng + math) div 2;
end;

function TStudent.name():String;
begin
result := nam;
end;

function TStudent.English():Integer;
begin
result := eng;
end;

function TStudent.Mathematics():Integer;
begin
result := math;
end;

function TStudent.Average():Integer;
begin
result := ave;
end;

end.

実行結果


S:\>lesson005\project1.exe
柴田望洋
英語= 100
数学= 100
平均= 100
増田真二
英語= 80
数学= 80
平均= 80