首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2012-09-08 
清问大家为什么在结构体中不能够初始化成员#include stdafx.h#include iostreamusing std::cinusing

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

#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; 

热点排行