相关疑难解决方法(0)

为什么C++支持在结构中成员分配数组,但一般不支持?

我理解不支持成员分配数组,因此以下方法不起作用:

int num1[3] = {1,2,3};
int num2[3];
num2 = num1; // "error: invalid array assignment"
Run Code Online (Sandbox Code Playgroud)

我只是接受了这个事实,认为该语言的目的是提供一个开放式框架,并让用户决定如何实现诸如复制数组之类的东西.

但是,以下工作正常:

struct myStruct { int num[3]; };
struct myStruct struct1 = {{1,2,3}};
struct myStruct struct2;
struct2 = struct1;
Run Code Online (Sandbox Code Playgroud)

该数组num[3]是从其实例中成员分配struct1到其实例中的struct2.

为什么结构支持成员方式的数组,但一般情况下不支持?

编辑:Roger Pate 在结构中的线程std :: string中的注释- 复制/赋值问题?似乎指向答案的大致方向,但我不知道自己确认.

编辑2:许多出色的回应.我之所以选择Luther Blissett,是因为我对这种行为背后的哲学或历史原理很感兴趣,但James McNellis对相关规范文档的引用也很有用.

c c++ arrays struct variable-assignment

82
推荐指数
2
解决办法
7481
查看次数

数组标识符和数组标识符地址的区别

我认为以下程序会清楚地说明我的疑问,所以我发布了该程序:

 #include <stdio.h>
int main() {

        int a[]={1,2,3,4,5};
        if(&a[0] == a)
                printf("Address of first element of an array is same as the value of array identifier\n");
        if(&a == a)
                printf("How can a value and address of an identifier be same?!");

        return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是输出链接:http : //ideone.com/KRiK0

c

3
推荐指数
1
解决办法
2975
查看次数

标签 统计

c ×2

arrays ×1

c++ ×1

struct ×1

variable-assignment ×1