#include<iostream>
using namespace std;
class Shape
{
private:
int no;
};
inline void
Point::setX(int ix){x = ix;}
inline void
Point::setY(int iy){y = iy;}
inline void
Point::getX(){return x;}
Point::getY(){return y;}
class Rectangle:public Shape
{
private:
int width;
int height;
Point* leftUp;
public:
Rectangle(int width,int height,int x,int y);
Rectangle(const Rectangle& other);
Rectangle& operator = (const Rectangle& other);
~Rectangle();
int getWidth();
int getHeight();
};
Rectangle::Rectangle(int width,int height,int x,int y):width(width),height(height)
{
leftUp = new Point();
leftUp ->setX(x);
leftUp->setY(y);
}
Rectangle::Rectangle(const Rectangle& other)
{
this->height = other.height;
this->width = other.width;
delete leftUp;
this->leftUp = new Point();
this->leftUp = setX(other.leftUp->getX());
this->leftUp = setY(other.leftUp->getY());
}
this->leftUp = setX(other.leftUp->getX());
this->leftUp = setY(other.leftUp->getY());
Q:
典型拷贝构造函数:
1. 考虑空值
2.非指针的成员要单独处理
3.{ }里只对指针成员做处理,其它全部放在初始化列表
4.初始化列表里的顺序与你的标准顺序一致
修改后的拷贝构造函数:
Rectangle::Rectangle(const Rectange& other)
:Shape(other),heigth(other.heigth),width(other.width)
{
if(other.leftUp != nullptr){
this->leftUp = new Point(*other.leftUp);
}else
{
this->leftUp = nullptr;
}
}
Rectangle&
Rectangle::operator = (const Rectangle& other)
{
if(this != &other){
this->height = other.height;
this->width = other.width;
delete leftUp;
this->leftUp = new Point();
this->leftUp = setX(other.leftUp->getX());
this->leftUp = setY(other.leftUp->getY());
return *this;
}else{
return *this;
}
}
1.
Rectangle(int width,int height,int x,int y):
Shape(),width(width),height(height),leftUp(new Point(x,y)){}
Shape( )没有必要去写,默认调用父类的构造函数
2.
Rectangle(const Rectangle& other):
Shape(),width(other.width),height(other.height),leftUp(new Point(*other.leftUp)){}
Shape(other)
没有判断other.leftUp是否为空