Skip to content

Instantly share code, notes, and snippets.

@terasakisatoshi
Created November 26, 2024 06:58
Show Gist options
  • Select an option

  • Save terasakisatoshi/5b6771b0f33788eee9b04071441ec44c to your computer and use it in GitHub Desktop.

Select an option

Save terasakisatoshi/5b6771b0f33788eee9b04071441ec44c to your computer and use it in GitHub Desktop.
C++ 継承練習
/*
https://rinatz.github.io/cpp-book/ch07-03-inheritance/
*/
#include <iostream>
class Rectangle {
public:
Rectangle(int h, int w): height_(h), width_(h) {};
int Area() const {
return height_ * width_;
}
int height_;
int width_;
};
class Square : public Rectangle {
public:
Square(int size) : Rectangle(size, size){}
};
int calcArea(Rectangle rect){
int h = rect.width_;
int w = rect.height_;
std::cout << "calcArea for Rectangle ";
return h * w;
}
int calcArea(Square rect){
int h = rect.width_;
std::cout << "calcArea for Square ";
return h * h;
}
int main() {
Rectangle r(10, 5);
Square s(20);
std::cout << r.Area() << std::endl;
std::cout << calcArea(r) << std::endl;
std::cout << s.Area() << std::endl;
std::cout << calcArea(s) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment