开发者

Regarding the copying of objects [duplicate]

This question already has answers here: 开发者_Go百科 Closed 12 years ago.

Possible Duplicate:

Why does C++ support memberwise assignment of arrays within structs, but not generally?

Why is it that we can assign the object of one structure to other directly example:

struct student s1,s2;
s2=s1 //is perfectly ok.

but we can not assign one array value to the other eg:

int a[10],b[10];
a=b //is not allowed.

though the element of structure may contain any no of arrays.

Please Explain.


Array assignment is not allowed at language level for purely historical reasons. Check also this question.


Ultimately, I don't think there is a reason that has much in the way of theoretical basis. I'd guess that it comes down to an expectation that arrays are typically large enough that preventing accidental copying was worthwhile.

By contrast, I think the expectation was that structs would typically be small enough that the convenience of supporting assignment outweighed the risk of possibly doing something unexpectedly expensive.


This is how it is specified to be. If you need assignable arrays, use std::vector:

std::vector< int> a(10), b(10);
a = b;

The rule for default assignment operator for structs (and classes) is that it calls the assignment operators for base structs/classes and then the assignment operators for each data member.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜