简体   繁体   中英

How to get a reference in a struct of the same struct in my code

I have this struct, but I get some errors when I mention a reference to its own type:

struct Point  {
              int x;
              int y;

              bool isLattice;

              Vect2D gradient;

              ///used only when isLattice is false
              Point p00; ///top-left corner
              Point p01; ///top-right corner
              Point p10; ///bottom-left corner
              Point p11; ///bottom-right corner

              ///the displacement vectors  Gradient-this.Vect2D
              Vect2D disp00;
              Vect2D disp01;
              Vect2D disp10;
              Vect2D disp11;  ///used along the gradient vector of the lattice points

              ///the Q-s for each corner Q= Disp*G which are going to be used for the interpolation
              double q00;
              double q01;
              double g10;
              double q11;

          };

I need to know how I should initialize this struct, because this is how I used to do it in the past in other codes. What is the error in this one?

I would guess you're coming from a managed language

struct Point  {
    //...
    Point p00; 
    // ...
}

This is your problem. Objects in C++ are NOT references. This puts an instance of Point inside an instance of Point. How will that work? You could use a pointer, or a reference.

Change

Point p00;

to

Point & p00; // this requires being initialized  
             // in the constructor initialization list

or maybe

std::shared_ptr<Point> p00;

Change Point pX; to Point * pX; .

This way, the code will compile, and you get to initialise the Point pointers using an appropriate constructor.

为什么不在 Point 实例中使用另一种类型的结构?

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