teaching machines

CS 330 Lecture 26 – C++ I/O, Overloading, References

April 8, 2015 by . Filed under cs330, lectures, spring 2015.

Agenda

TODO

Code

Image.h

#ifndef IMAGE_H
#define IMAGE_H

#include <iostream>

#include <string>

namespace cs330 {
  class Image {
    public:
      Image(int width, int height);
      Image(std::string path);
      ~Image();

      int GetWidth() const;
      int GetHeight() const;

      unsigned char operator()(int r, int c) const;

    private:
      int width;
      int height;
      unsigned char *pixels;
  };
}

std::ostream& operator<<(std::ostream &out, const cs330::Image &image);

#endif

Image.cpp

#include <fstream>

#include "Image.h"

namespace cs330 {

Image::Image(int width, int height) :
  // The C++ way:
  width(width),
  height(height) {
  // The Java way:
  /* this->width = width; */
  /* this->height = height; */
  pixels = new unsigned char[width * height];
}

Image::Image(std::string path) {
  std::ifstream in(path.c_str());
  std::string wasted;
  int max;
  in >> wasted >> width >> height >> max;

  // TODO read pixels
  pixels = new unsigned char[width * height];
  for (int i = 0; i < width * height; ++i) {
    int igray;
    in >> igray;
    pixels[i] = (unsigned char) igray;
  }

  in.close();
}

Image::~Image() {
  delete[] pixels;
}

int Image::GetWidth() const {
  return width; 
}

int Image::GetHeight() const {
  return height;
}

unsigned char Image::operator()(int r, int c) const {
  return pixels[c + r * GetWidth()];
}

}

std::ostream& operator<<(std::ostream &out, const cs330::Image &image) {
  out << "P2" << std::endl;
  out << image.GetWidth() << " " << image.GetHeight() << std::endl;
  out << 255 << std::endl;

  // write pixels
  for (int r = 0; r < image.GetHeight(); ++r) {
    for (int c = 0; c < image.GetWidth(); ++c) {
      out << (int) image(r, c) << std::endl;
    }
  }

  return out;
}

main.cpp

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

/* using namespace cs330; */
/* using cs330::Image; */

int main(int argc, char **argv) {
  cs330::Image before(argv[1]);
  // do something to before
  
  std::cout << before;

  return 0;
}

Haiku

onĀ earning the right
Try your spinach, dear
In this house we are good eaters
Or informed haters