関数の多重定義

Cプログラマのための C++入門 > 1. C++ に慣れよう >

関数の多重定義

C++


#include <stdio.h>

int abs(int x)
{
return (x < 0 ? -x : x);
}
long abs(long x)
{
return (x < 0L ? -x : x);
}
double abs(double x)
{
return (x < 0.0 ? -x : x);
}

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

printf("abs(-6) = %d\n", abs(-6));
printf("abs(-7L) = %ld\n", abs(-7L));
printf("abs(-7.9) = %f\n", abs(-7.9));

return 0;
}

実行結果


R:\>lesson001\project1.exe
abs(-6) = 6
abs(-7L) = 7
abs(-7.9) = 7.900000

Delphi


program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils;

function abs(x:Longint):Longint; overload;
begin
if x < 0 then
result := -x
else
result := x;
end;

function abs(x:Real):Real; overload;
begin
if x < 0 then
result := -x
else
result := x;
end;

procedure main();
begin
Writeln(Format('abs(-6) = %d', [abs(-6)]));
Writeln(Format('abs(-7L) = %d', [abs(Longint(-7))]));
Writeln(Format('abs(-7.9) = %f', [abs(-7.9)]));
end;

begin
main;
end.

実行結果


S:\>lesson001\project1.exe
abs(-6) = 6
abs(-7L) = 7
abs(-7.9) = 7.90