CS 330 Lecture 25 – Concrete Classes in C++
Agenda
- what ?s
- classes in C++
- namespaces
- RAII
- references
- overloading builtin operators
- I/O of custom types
Code
Image.h
#ifndef IMAGE_H
#define IMAGE_H
#include <string>
namespace cs330 {
class Image {
public:
Image(int width, int height);
Image(std::string path);
~Image();
private:
int width;
int height;
unsigned char *pixels;
};
}
#endif
Image.cpp
#include "Image.h"
namespace cs330 {
Image::Image(int width, int height) :
width(width),
height(height) {
// The Java way:
/* this->width = width; */
/* this->height = height; */
pixels = new unsigned char[width * height];
}
Image::Image(std::string path) {
ifstream in(path.c_str());
std::string wasted;
// read p2
in >> wasted;
// read width
in >> this->width;
// read height
in >> this->height;
// read max
int max;
in >> max;
// read all pixels
in.close();
}
Image::~Image() {
delete[] pixels;
}
}
main.cpp
#include <iostream>
#include "Image.h"
/* using namespace cs330; */
/* using cs330::Image; */
int main(int argc, char **argv) {
/* Image img = Image(512, 256); */
cs330::Image img(512, 256);
cs330::Image *img2 = new Image(3000, 256);
// img's destructor automatically called for us
// img2's destructor awaits our future delete
// delete img2;
return 0;
}
Haiku
on picking the best
With lots of parameters
And an RNG
best
is a functionWith lots of parameters
And an RNG