为什么可以这么初始化?

独酌逸醉 2010-09-14 12:03:44

// TestVS2008.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

template <class T,size_t N>
struct block {
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;

typedef ptrdiff_t difference_type;
typedef size_t size_type;
typedef pointer iterator;
typedef const_pointer const_iterator;

iterator begin() { return data; }
iterator end() const { return data + N; }

reference operator[] (size_type n) { return data[n]; }
const_reference operator[] (size_type n) const { return data[n]; }

size_type size() const { return N; }
T data[N];
};

int _tmain(int argc, _TCHAR* argv[])
{
block<int,5> b = {1,2,3,4,5}; // b不是一个数组为什么可以这样初始化?
for (int i = 0; i < b.size() ; ++ i)
cout << b[i] << ' ';
return 0;
}


...全文
90 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengzhixi 2010-09-14
  • 打赏
  • 举报
回复
好了,可以结贴了。
lovestefanie 2010-09-14
  • 打赏
  • 举报
回复
囧,可以的吧
Csuxiaowu 2010-09-14
  • 打赏
  • 举报
回复
找到了 396页
Csuxiaowu 2010-09-14
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 pgplay 的回复:]

对于没有定义构造函数并且其全体数据成员均为 public 的类,可以采用与初始化数组元素相同的方式初始化其成员——C++ Primer
[/Quote]
我翻书找了半天没找到啊 告诉我下哪页?多谢了
Csuxiaowu 2010-09-14
  • 打赏
  • 举报
回复
我擦 什么东西 定义来定义去的
没见过这种初始化
Python ??
ri_aje 2010-09-14
  • 打赏
  • 举报
回复
C++03 8.5.1.[1,2]


1 An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

2 When an aggregate is initialized the initializer can contain an initializer-clause consisting of a brace-enclosed, comma-separated list of initializer-clauses for the members of the aggregate, written in increasing subscript or member order. If the aggregate contains subaggregates, this rule applies recursively to the members of the subaggregate.

[Example:
struct A {
int x;
struct B {
int i;
int j;
} b;
} a = { 1, { 2, 3 } };
initializes a.x with 1, a.b.i with 2, a.b.j with 3. ]



block<int,5> 是个 aggregate
耍宝王 2010-09-14
  • 打赏
  • 举报
回复
对于没有定义构造函数并且其全体数据成员均为 public 的类,可以采用与初始化数组元素相同的方式初始化其成员——C++ Primer
hqm475 2010-09-14
  • 打赏
  • 举报
回复
这是数组的初始化的一种方式啊,你也可以用循环给每个b[T]赋值
独酌逸醉 2010-09-14
  • 打赏
  • 举报
回复
恩,结贴!

64,676

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧