聚合体Aggregate

一、什么是聚合体呢?

英文表述为Aggregate, 从MSDN上找到的定义如下:

An aggregate type is an array, class, or structure type which:

  • Has no constructors

  • Has no nonpublic members

  • Has no base classes

  • Has no virtual functions

经过Ubuntu和VS2010验证,一个Aggregate,无论其成员是不是Aggregate,此Aggregate都是可以用{}来初始化。

http://msdn.microsoft.com/en-us/library/sdwe79a4.aspx


另外,MSDN 告诉我们一个聚合体是可以通过{}这种方式来初始化的。


而我们知道c语言里struct是能用{}这种方式来初始化的,而且是完全符合Aggregate的上述定义的。所以,我们可以得出一个结论,c语言里struct的行为就是一个Aggregate的行为。所以,c++中只要class和struct也象c语言里struct一样,满足成为一个Aggregate的条件,即能通过{}这种方式来初始化(不调用构造函数)。


二、举例说明

1>例1
struct Node
{
    int a;
    int b

};

struct Node node = {1,2};  ----编译correct,因为此例子就是一个Aggregate

VS2010里,通过“Ctrl + Alt + D”即可进入到c++代码和汇编的混合代码,查看汇编代码可知确实是没有调用struct的构造函数。


2>例2

class Test
{
public:
  Test() {};

private:
  int a;
};

struct Node
{
    int a;
    int b;
    Test c;
};

struct Node node = {1,2};  -----编译correct, 因为此例子struct Node是一个Aggregate。

3>例3

class Test
{
public:
  int a;
};

struct Node
{
    int a;
    int b;
    Test c;

};
struct Node node = {1,2};  -----编译correct, struct Node是一个Aggregate

4>例4

class Test
{
private:
  int a;
};

Test m = {1}  -------编译incorrect,因为int a不是public的,故class Test不是一个Aggregate

5>例5

class Test
{
   Test() { }
public:
   int a;
};

Test m = {1}  -------编译incorrect,因为Test有自定义的构造函数,故class Test不是一个Aggregate
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值