C++继承的虚函数问题

maoxuechun 2016-09-30 10:51:18
自定义类表示矩形(Rectangle)。
要求:
1、 有成员属性width(长,int),成员属性height(宽,int)。
2、 将width和height设置为私有属性,并提供公开的get,set函数。
3、 有合理的构造函数,构造函数必须初始化height和width。

自定义类表示正方形(Square)继承自矩形(Rectangle)
要求:
1、 改写父类的set函数,保证当正方形修改变长时长和宽都会改变。
2、 有合理的构造函数,构造函数必须初始化Rectangle

自己的代码:
头文件:
#ifndef RECTANGLE_H_
#define RECTANGLE_H_

class Rectangle
{
public:
Rectangle(const int& width=1,const int& height=1)
:width(width),height(height){}
virtual void setWidth(const int& width){this->width=width;}
int getWidth()const{return width;}
virtual void setHeight(const int& height){this->height=height;}
int getHeight()const{return height;}
private:
int width;
int height;
};

cpp文件:
#include "rectangle.h"
#include <iostream>
using namespace std;

Square::Square(const int& width,const int& height)
{
if(width!=height)
{
cout<<"width,height must be same"<<endl;
}
Rectangle(width,width);
}

/*
因为父类的成员是私有的,重写后,私有类的共有函数接口没有了,直接调用不行,用父类::set函数也不行
*/
void Square::setWidth(const int& width)
{
this->width=width;
if(getHeight()!=width)
{
setHeight(width);
}
}

void Square::setHeight(const int& height)
{
/*
this->height=height;
this->width=height;
*/
}
...全文
526 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhxingway 2016-10-11
  • 打赏
  • 举报
回复
void Square::setWidth(const int& width)
{
        Rectangle::setWidth(width);
       if(getHeight()!=width)
        {
        Rectangle::setHeight(width);
        }
}
看看你的子类头文件定义是什么,继承的时候加个public
微book 2016-10-10
  • 打赏
  • 举报
回复
void Square::setWidth(const int& width) { Rectangle::setWidth(width); if(getHeight()!=width) { setHeight(width); } }
maoxuechun 2016-10-09
  • 打赏
  • 举报
回复
是啊!但是偏偏有个这样的题目,我很苦恼··········我在网上查了下好想有种指针的方式,但是看不懂·······
微book 2016-10-05
  • 打赏
  • 举报
回复
派生类不能访问基类私有成员
Saleayas 2016-10-04
  • 打赏
  • 举报
回复
为什么不能用 __base::setXXX 函数呢? 是可以得。
maoxuechun 2016-10-04
  • 打赏
  • 举报
回复
因为我在里面实验了的,用父函数里面的设置函数编译器就报错
maoxuechun 2016-10-03
  • 打赏
  • 举报
回复
问题就是父函数重写后怎么访问父函数的私有成员,实现题目的要求
ztenv 版主 2016-10-03
  • 打赏
  • 举报
回复
你的问题是什么呢?

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧