第2回 C++教室

クラスの初歩

クラスとは,オブジェクトを作成するための仕組みのことです. C言語でいうところの構造体に,関数が組み合わさったものです. クラスの変数を宣言するとそれに対して関数を呼び出したり, 内包する変数の値を変更・参照することができます.

サンプル1

Block.h

#pragma once

class Block
{
public:
  int x1, y1, x2, y2;
  int v;

  Block(int x1_, int y1_, int x2_, int y2_, int v_ = 0) : x1(x1_), y1(y1_), x2(x2_), y2(y2_), v(v_) {}
};

test1.cpp

#include <iostream>
#include "Block.h"

using namespace std;

void main()
{
  Block b1(10, 20, 20, 30, 100);
  Block b2(10, 20, 15, 25);

  cout << "b1の頂点:" << " ( " << b1.x1 << " , " << b1.y1 << " ) - ( "
                               << b1.x2 << " , " << b1.y2 << " )" << endl;

  cout << "b1の値:" << b1.v << endl;

  cout << "b2の頂点:" << " ( " << b2.x1 << " , " << b2.y1 << " ) - ( "
                               << b2.x2 << " , " << b2.y2 << " )" << endl;

  cout << "b2の値:" << b2.v << endl;

}

サンプル2

Block.h

#pragma once

class Block
{
public:
  int x1, y1, x2, y2;
  int v;

  Block(int x1_, int y1_, int x2_, int y2_, int v_ = 0) : x1(x1_), y1(y1_), x2(x2_), y2(y2_), v(v_) {}
  int getArea();
};

Block.cpp

#include "Block.h"

int Block::getArea()
{
  int a = (x2 >= x1) ? (x2 - x1) : (x1 - x2);
  int b = (y2 >= y1) ? (y2 - y1) : (y1 - y2);

  return (a*b);
}

test2.cpp

#include <iostream>
#include "Block.h"

using namespace std;

void main()
{
  Block b1(10, 20, 20, 30, 100);
  Block b2(15, 20, 10, 25);

  cout << "b1の頂点:" << " ( " << b1.x1 << " , " << b1.y1 << " ) - ( "
                               << b1.x2 << " , " << b1.y2 << " )" << endl;

  cout << "b1の値:" << b1.v << endl;

  cout << "b1の面積:" << b1.getArea() << endl;

  cout << "b2の頂点:" << " ( " << b2.x1 << " , " << b2.y1 << " ) - ( "
                               << b2.x2 << " , " << b2.y2 << " )" << endl;

  cout << "b2の値:" << b2.v << endl;

  cout << "b2の面積:" << b2.getArea() << endl;

}