简体   繁体   English

如何在我的代码中获取相同结构的结构中的引用

[英]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. C++ 中的对象不是引用。 This puts an instance of Point inside an instance of Point.这会将 Point 的实例放入 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;改变Point pX; to Point * pX; Point * pX; . .

This way, the code will compile, and you get to initialise the Point pointers using an appropriate constructor.这样,代码将被编译,并且您可以使用适当的构造函数初始化 Point 指针。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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