teaching machines

CS 330 Lecture 22 – Custom types in C++

March 28, 2012 by . Filed under cs330, lectures, spring 2012.

Agenda

TODO

Code

Vector.h

#ifndef VECTOR_H
#define VECTOR_H

class Vector2 {
  public:
    Vector2();
    Vector2(float x, float y);

    // write a subscript operator
    float& operator[](int index);

    Vector2 operator+(const Vector2& other);

    // overload a print operator

  private:
    float x;
    float y;
};

#endif

Vector.cpp

#include <cassert>
#include "Vector.h"

Vector2::Vector2() :
  x(0.0f),
  y(0.0f) {
}   

Vector2::Vector2(float x, float y) :
  x(x),
  y(y) {
}

float& Vector2::operator[](int index) {
  assert(index >= 0 && index <= 1);  
  return index == 0 ? x : y;
}

Vector2 Vector2::operator+(const Vector2& other) {
  return Vector2(x + other.x, y + other.y);  
}

/* ------------------------------------------------------------------------- */

drawer.cpp

#include <iostream>

#include "Vector.h"

int main() {
  Vector2 point(10.0f, 15.0f);
  Vector2 point2(1.0f, 2.0f);
  Vector2 sum = point + point2;
  std::cout << "sum[0]: " << sum[0] << std::endl;
  std::cout << "sum[1]: " << sum[1] << std::endl;

  std::cout << "point[0]: " << point[0] << std::endl;
  std::cout << "point[1]: " << point[1] << std::endl;

  point[0] = 11.0f;

  std::cout << "point[0]: " << point[0] << std::endl;
  std::cout << "point[1]: " << point[1] << std::endl;

  /* point[0] // point.getX() */
  /* point[1] // point.getY() */
}

Haiku

Types grow a language.
Without changing its grammar.
And C++ lives.