一次误用栈导致的错误。

来源:互联网 发布:2009网络流行歌曲大全 编辑:程序博客网 时间:2024/06/10 15:46
#include<iostream.h>// rough implementation class Point{public:    Point(int _x=0,int _y=0)    {        x = _x;        y = _y;    }    int x;    int y;};class Rectangle:public Point{public:     int width;     int height;     Point * leftUp;     Point * rightDown;     Rectangle(int width, int height, int x, int y);     Rectangle(const Rectangle& other);     Rectangle& operator=(const Rectangle& other);     ~Rectangle();};inlineRectangle::Rectangle(int width,int height,int x,int y){    int _x = x;    int _y = y;    int _height = height;    int _width = width;    Point p1(  _x,_y);    leftUp = &p1;    Point p2(_x+_width,_y+_width);    rightDown = &p2;};inlineRectangle::~Rectangle(){//  delete leftUp;//  delete rightDown;}void main(){    Rectangle rect1(2,2,2,2);    cout<<"("<<rect1.leftUp->x<<","<<rect1.leftUp->y<<")"<<endl;    cout<<rect1.rightDown->x<<endl;};

这里写图片描述

问题解决:
栈空间在{}执行完后,会被释放。必须用new出来的,放在heap即堆里面才可以。
下面是源代码:

#include<iostream.h>class Point{public:    Point(int _x=0,int _y=0)    {        x = _x;        y = _y;    }    int x;    int y;};class Rectangle:public Point{public:     int width ;     int height;     Point * leftUp;     Point * rightDown;     Rectangle(int width, int height, int x, int y);     Rectangle(const Rectangle& other);     Rectangle& operator=(const Rectangle& other);     ~Rectangle();};inline Rectangle::Rectangle(int width,int height,int x,int y){    int _x = x;    int _y = y;    int _height = height;    int _width = width;    leftUp = new Point(_x,_y);    rightDown = new Point(_x+width,_y+height);};inlineRectangle::Rectangle(const Rectangle& other){    width = other.width;    height = other.height;    leftUp = new Point(other.leftUp->x,other.leftUp->y);    rightDown = new Point(other.rightDown->x,other.rightDown->y);};inlineRectangle& Rectangle::operator=(const Rectangle& other){    if(this == &other)        return *this;    delete leftUp;    leftUp = new Point(other.leftUp->x,other.leftUp->y);    delete rightDown;    rightDown = new Point(other.rightDown->x,other.rightDown->y);    return *this;};inlineRectangle::~Rectangle(){    delete leftUp;    delete rightDown;};void main(){    Rectangle rect1(2,2,2,2);    cout<<"("<<rect1.leftUp->x<<","<<rect1.leftUp->y<<")"<<endl;    cout<<"("<<rect1.rightDown->x<<","<<rect1.rightDown->y<<")"<<endl;    Rectangle rect2(rect1);    cout<<"("<<rect2.leftUp->x<<","<<rect2.leftUp->y<<")"<<endl;    cout<<"("<<rect2.rightDown->x<<","<<rect2.rightDown->y<<")"<<endl;    Rectangle rect3(3,3,3,3);    rect3 = rect1;    cout<<"("<<rect3.leftUp->x<<","<<rect3.leftUp->y<<")"<<endl;    cout<<"("<<rect3.rightDown->x<<","<<rect3.rightDown->y<<")"<<endl;};

Github:
里面主要也没什么优化,主要就是把实验代码改成了h文件和cpp文件分开了。
https://github.com/juedaiyuer/GeekBand-CPP-1501-Homework/tree/master/G2015010148

0 0