C++におけるオブジェクト
C++ では、クラス(class)を具象化したものがオブジェクト(object)です。例えて言うなら、クラスは鋳型でオブジェクトは鋳型から作られる鋳物です。C++ のオブジェクトは Java のインスタンス(instance)に相当します。
下記の例では、Robot がクラス、robot、robot0、*robot1、robot00、*robot11 がオブジェクトです。
robot.hpp
#pragma once
class Robot {
double x, y;
public:
static const int robots;
Robot(double x = 0, double y = 0);
~Robot();
auto set(double, double) -> void;
auto getX() const -> double;
auto getY() const -> double;
auto move(double, double) -> void;
auto show() const -> void;
};
robot.cpp
#include <cstdio>
#include "robot.hpp"
const int Robot::robots = 10;
Robot::Robot(double x, double y) : x{x}, y{y} {}
Robot::~Robot() {}
auto Robot::set(double x, double y) -> void {
this->x = x;
this->y = y;
}
auto Robot::getX() const -> double {
return x;
}
auto Robot::getY() const -> double {
return y;
}
auto Robot::move(double dx, double dy) -> void {
x += dx;
y += dy;
}
auto Robot::show() const -> void {
printf("(x, y) = (%5.3f, %5.3f)\n", x, y);
}
main.cpp
#include "robot.hpp"
auto main() -> int {
//Robot robot;
//Robot robot{0, 0};
Robot robot = {0, 0};
robot.move(1, 1);
robot.show();
//auto robot0 = Robot; /* NG */
//auto robot0 = Robot();
//auto robot0 = Robot(0, 0);
auto robot0 = Robot{0, 0};
robot0.move(1, 1);
robot0.show();
//auto robot1 = new Robot;
//auto robot1 = new Robot();
//auto robot1 = new Robot(0, 0);
auto robot1 = new Robot{0, 0};
robot1->move(1, 1);
robot1->show();
delete robot1;
const int length = 10;
Robot robot00[length];
//Robot robot00[Robot::robots]; /* NG */
for (int i = 0; i < length; i++) {
robot00[i] = {0, 0};
robot00[i].move(1, 1);
robot00[i].show();
}
auto robot11 = new Robot[Robot::robots];
for (int i = 0; i < Robot::robots; i++) {
robot11[i] = {0, 0};
robot11[i].move(1, 1);
robot11[i].show();
}
delete[] robot11;
}
〈コンパイル〉
g++ -std=c++17 -O3 -pedantic-errors -s -Wall -static *.cpp -o main.exe strip main.exe
〈コンパイル〉
g++ -std=c++17 -O3 -pedantic-errors -s -Wall -c robot.cpp -o robot.o g++ -std=c++17 -O3 -pedantic-errors -s -Wall -static robot.o main.cpp -o main.exe strip main.exe
参考サイト