简体   繁体   English

结构类型的元素数组存在问题

[英]Problem with array of elements of a structure type

I'm writing an app in Visual Studio C++ and I have problem with assigning values to the elements of the array, which is array of elements of structure type. 我在Visual Studio C ++中编写一个应用程序,但在将值分配给数组元素时遇到了问题,数组元素是结构类型的元素数组。 Compiler is reporting syntax error for the assigning part of the code. 编译器正在报告代码分配部分的语法错误。 Is it possible in anyway to assign elements of array which are of structure type? 无论如何,是否有可能分配结构类型的数组元素?

typedef struct {
    CString x;
    double y;
} Point;


Point p[3];
p[0] = {"first", 10.0};
p[1] = {"second", 20.0};
p[2] = {"third", 30.0};

Give your struct a constructor: 给您的结构构造函数:

struct Point {
    CString x;
    double y;
   Point( const CString & s = "" , double ay = 0.0 ) : x(s), y(ay) {}
};

You can then say: 然后您可以说:

Point p[3];
p[0] = Point( "first", 10.0 );

You can use an initializer when the array is being declared: 声明数组时可以使用初始化程序:

struct Point{
    CString x;
    double y;
};

Point p[3] = {
  {CString("first"), 10.0},
  {CString("second"), 20.0},
  {CString("third"), 30.0}
};

But not on assignment. 但不是分配。

You can not set your data in this way. 您不能以这种方式设置数据。 Instead write: 而是写:

p[0].x = "first": p[0].y = 10.0;
...

What Neil says is right indeed!! 尼尔所说的确实是正确的!

Some more info here... 一些更多的信息在这里...

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

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