C数据成员初始化器是不允许的

前端之家收集整理的这篇文章主要介绍了C数据成员初始化器是不允许的前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我全新的C,所以忍受我.我想用一个静态数组做一个类,并从main中访问这个数组.这是我想在C#中做的.
  1. namespace ConsoleApplication1
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. Class a = new Class();
  8. Console.WriteLine(a.arr[1]);
  9.  
  10. }
  11. }
  12. }
  13.  
  14. =====================
  15.  
  16. namespace ConsoleApplication1
  17. {
  18. class Class
  19. {
  20. public static string[] s_strHands = new string[]{"one","two","three"};
  21. }
  22. }

这是我试过的:

  1. // justfoolin.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <string>
  6. #include <iostream>
  7. using namespace std;
  8.  
  9. class Class {
  10.  
  11. public:
  12. static string arr[3] = {"one","three"};
  13. };
  14.  
  15.  
  16. int _tmain(int argc,_TCHAR* argv[])
  17. {
  18. Class x;
  19. cout << x.arr[2] << endl;
  20. return 0;
  21. }

但我得到:
IntelliSense:不允许使用数据成员初始化器

解决方法

您需要稍后执行初始化;您不能在类定义中初始化类成员. (如果可以的话,在头文件中定义的类将会导致每个翻译单元定义自己的成员副本,让链接器弄乱一些.)
  1. class Class {
  2. public:
  3. static string arr[];
  4. };
  5.  
  6. string Class::arr[3] = {"one","three"};

类定义定义了与实现分开的接口.

猜你在找的C&C++相关文章