读书人

清问大伙为什么在结构体中不能够初始化

发布时间: 2012-09-08 10:48:07 作者: rapoo

清问大家为什么在结构体中不能够初始化成员

#include "stdafx.h"
#include <iostream>;
using std::cin;
using std::cout;
using std::endl;
struct test
{
int a;
staticint b=2;

} a;

int _tmain(int argc, _TCHAR* argv[])
{
a.a=2;
cout<<a.a<<a.b<<endl;

return 0;
}

错误3error C2864: “test::b”: 只有静态常量整型数据成员才可以在类中初始化
怎么老是提示这个啊!!!!!!!!!!!!!!!!!!!
我加了static不行吗???

[解决办法]

C/C++ code
1)#include  <iostream>using std::cin; using std::cout; using std::endl;struct test {     int a;     static const int  b=2; } a; int _tmain(int argc, _TCHAR* argv[]) {     a.a=2;     cout <<a.a <<a.b <<endl;     return 0; } 2)#include  <iostream>using std::cin; using std::cout; using std::endl;struct test {     int a;     static int  b;//=2; } a; int test::b = 2;int _tmain(int argc, _TCHAR* argv[]) {     a.a=2;     cout <<a.a <<a.b <<endl;     return 0; }
[解决办法]
探讨
C/C++ code
struct test
{
int a;
static int b;

};
int test::b=2;

[解决办法]
include <iostream>
using std::cin;
using std::cout;
using std::endl;
struct test
{
int a=9;
static int b;

} a;
int test::b=3;
int main()
{
a.a=2;
cout <<a.a <<endl<<test::b <<endl;

return 0;
}

[解决办法]
结构体只是一个数据类型的声明 要定义常量 需要添加 CONST

#include "stdafx.h"
#include<iostream>
using namespace std;
struct test
{
int a;
static const int b=2;

} a;

int _tmain(int argc, _TCHAR* argv[])
{
a.a=2;
cout <<a.a <<a.b <<endl;

return 0;
}

读书人网 >C++

热点推荐