简体   繁体   中英

Pointer to object created in parameter

I have a class called Rectangle which holds two pointers to objects of the class Point2D .

class Rectangle: public GeoObjekt
{
private:
    Point2D* lu;
    Point2D* ro;
public:
    Rectangle(Point2D lu, Point2D ro);
}

Rectangle::Rectangle(Point2D lu, Point2D ro) {
    this->lu = &lu;
    this->ro = &ro;
}

To create an object of this class, I call the following line:

Rectangle rectangle(Point2D(0, 0), Point2D(2, 1));

The constructor is working fine, but when I try to access Point2D* lu; or Point2D* ro; , I get an access violation exception:

Exception thrown at 0xFEDC8589 in Rectangle.exe: 0xC00005: Access violation while executing at position 0xFEDC8589.

I checked it with the debugger and the values inside Point2D* lu; or Point2D* ro; are completely different from the values they initially had. They change after leaving the constructor.

Can someone tell me what I am doing wrong?

Note: The line Rectangle rectangle(Point2D(0, 0), Point2D(2, 1)); should remain as it is.

Change the members lu and ro to be Point2D instead of Point2D* .

The Point2D s you supplied in the constructor are destroyed on the next line, so your pointers end up pointing at nothing (dangling pointers).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM