题解 | #求长方体表面积#

多态实现求面积体积

http://www.nowcoder.com/practice/826ed8e0d67042c49e32a7293c873538

#include<bits/stdc++.h>
using namespace std;
class rectangle {
  private:
    int length, width;
  public:
    rectangle(int x, int y) {
        length = x;
        width = y;
    }
    void set(int x, int y) {
        length = x;
        width = y;
    }
    int getlength() {
        return length;
    }
    int getwidth() {
        return width;
    }
    // write your code here...
    //多态关键字virtual,父类声明,也可以实现(面积)
    virtual int getval(){
        return this->length*this->width;
    }

};
class cuboid: public rectangle {
  private:
    int height;
  public:
    cuboid(int x, int y, int z): rectangle(x, y) {
        height = z;
    }
    // write your code here...
    //子类重写,实现体积
    virtual int getval(){
        return this->rectangle::getval()*this->height;
    }

};
int main() {
    int x, y, z;
    cin >> x >> y >> z;
    cuboid a(x, y, z);
    rectangle b(x, y);

    rectangle* p = &b;
    cout << p->getval() << '\n';

    p = &a;
    cout << p->getval();
    return 0;
}
全部评论

相关推荐

湫湫湫不会java:1.在校经历全删了2.。这些荣誉其实也没啥用只能说,要的是好的开发者不是好好学生3.项目五六点就行了,一个亮点一俩行,xxx技术解决,xxx问题带来xxx提升。第一页学历不行,然后啥有价值的信息也没有,到第二页看到项目了,第一个项目九点,第二个项目像凑数的俩点。总体给人又臭又长,一起加油吧兄弟
点赞 评论 收藏
分享
Gaynes:查看图片
点赞 评论 收藏
分享
评论
5
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务