Skip to content

Instantly share code, notes, and snippets.

@SimoneCheng
Last active December 8, 2024 04:31
Show Gist options
  • Save SimoneCheng/ca565783513b723195d2e1e83c62b324 to your computer and use it in GitHub Desktop.
Save SimoneCheng/ca565783513b723195d2e1e83c62b324 to your computer and use it in GitHub Desktop.
113-NTUT-problem-04.cpp
#include <iostream>
#include <string>
using namespace std;
class Shape {
protected:
string c; // color
int w; // weight
public:
string getC() { return "white"; };
virtual int getW() { return 0; }; // virtual function
virtual int getV() = 0; // pure virtual function /* problem 4-1 */
};
class Cube: public Shape {
private:
int s; // side
public:
Cube(string v1, int v2, int v3): s(v3) { setC(v1); setW(v2); };
void setC(string v) { c = v; };
void setW(int v) { w = v; };
int getS() { return s; };
string getC() { return c; };
string getC(Cube *o) { return c + o->getC(); }; // function overloading
virtual int getW() { return w; }
virtual int getV() { return s * s * s; };
Cube operator + (Cube& o) { // operator overloading /* problem 4-2 */
return Cube(getC() + o.getC(), getW() + o.getW(), getS() + o.getS());
}
};
int main() {
Shape *p1 = new Cube("cyan", 1, 2);
Cube *p2 = new Cube("blue", 3, 4);
Cube cube = Cube("red", 5, 6) + *p2;
cout << p1->getC() << endl; /* problem 4-3: white */
cout << p1->getW() << endl; /* problem 4-4: 1 */
cout << p2->getC() << endl; /* problem 4-5: blue */
cout << p2->getW() << endl; /* problem 4-6: 3 */
cout << cube.getC() << endl; /* problem 4-7: redblue */
cout << cube.getC(p2) << endl; /* problem 4-8: redblueblue */
cout << cube.getV() << endl; /* problem 4-9: 1000 */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment