C++继承的虚函数问题
自定义类表示矩形(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;
*/
}