免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3358 | 回复: 4
打印 上一主题 下一主题

结构体初始化,为什么int可以,换成string就不行了? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-01-10 18:09 |只看该作者 |倒序浏览
#include <string>
#include <iostream>
using namespace std;
main()
#if 0
{
       //error note:         
        // non-aggregates cannot be initialized with initializer list

        typedef struct test{
                string a;
                string b;
                int    c;
        };

        struct test *pins;
        struct test ins1={"abc","def",3};

        pins=&ins1;
       
        pins->a="aaa";
        pins->b="bbb";

       
}
#endif
#if 0
{
        // success!
        typedef struct test{
                int a;
                int b;
                int c;
        };

        struct test *pins;
        struct test ins1={1,2,3};

        pins=&ins1;
       
        pins->a=3;
        pins->b=3;
}
#endif

上面的提示错误,下面的就成功了。
通过MSDN查看:
The specified identifier was incorrectly initialized.
An initializer list is needed to initialize the following types:

An array

A class, structure, or union that does not have constructors, private or protected members, base classes, or virtual functions
上面的带有string的结构不是aggregates吗?

论坛徽章:
0
2 [报告]
发表于 2007-01-10 19:28 |只看该作者
string也是一个结构,于"123"类型不匹配,不能直接赋值

论坛徽章:
0
3 [报告]
发表于 2007-01-10 22:03 |只看该作者
string的定义typedef basic_string<char> string;

所以定义的struct就有了consturctor...

论坛徽章:
0
4 [报告]
发表于 2007-01-11 09:00 |只看该作者

我在AIX上是可以的!

我在AIX上是可以的!

论坛徽章:
0
5 [报告]
发表于 2007-01-11 15:35 |只看该作者
程序中定义的两种 test 类都属于 aggregate 类型,程序是合法的。

如果你的编译器给出了第一个 test 类是 non-aggregate 的信息,那应该是属于编译器的问题。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP