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.

Revisions

  1. SimoneCheng revised this gist Dec 8, 2024. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion 113-NTUT-problem-04.cpp
    Original file line number Diff line number Diff line change
    @@ -22,7 +22,7 @@ class Cube: public Shape {
    void setW(int v) { w = v; };
    int getS() { return s; };
    string getC() { return c; };
    string getC(Cube *o) { return c + o -> getC(); }; // function overloading
    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 */
  2. SimoneCheng renamed this gist Dec 8, 2024. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. SimoneCheng created this gist Dec 8, 2024.
    45 changes: 45 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    #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 */
    }