メンバ関数

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

メンバ関数

C++


#include <stdio.h>

struct student
{
public:
char name[20];
int eng;
int math;
private:
int ave;
public:
void calc_ave();
int average();
};

void student::calc_ave()
{
ave = (eng + math) / 2;
}

int student::average()
{
return ave;
}

int main(int argc, char* argv[])
{
student x;

x.eng = 60;
x.math = 70;

x.calc_ave();

printf("eng = %d\n", x.eng);
printf("math = %d\n", x.math);
printf("ave = %d\n", x.average());

return 0;
}

実行結果


R:\>lesson003\project1.exe
eng = 60
math = 70
ave = 65

Delphi


program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils;

type
TStudent = class
public
eng: Integer;
math: Integer;
private
ave: Integer;
public
procedure calc_ave();
function average():Integer;
end;

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

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

procedure main();
var
x: TStudent;
begin
x := TStudent.Create;
x.eng := 60;
x.math := 70;

x.calc_ave;

Writeln(Format('eng = %d', [x.eng]));
Writeln(Format('math = %d', [x.math]));
Writeln(Format('ave = %d', [x.average]));

x.Free;
end;

begin
main;
end.

実行結果


S:\>lesson003\project1.exe
eng = 60
math = 70
ave = 65