C ++数据成员的初始值是不允许的 [英] C++ data member initializer is not allowed

查看:111
本文介绍了C ++数据成员的初始值是不允许的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全新的C ++如此容忍我。我想和静态数组类,并获得这个数组从主。以下是我想在C#中的事情。

I totally new to C++ so bear with me. I want to make a class with a static array, and access to this array from the main. Here is what i want to do in C#.

   namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Class a = new Class();
                Console.WriteLine(a.arr[1]);

            }
        }
    }

    =====================

    namespace ConsoleApplication1
    {
        class Class
        {       
            public static string[] s_strHands = new string[]{"one","two","three"};
        }
    }

下面是我曾尝试:

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

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

class Class {

  public:
      static string arr[3] = {"one", "two", "three"};
};


int _tmain(int argc, _TCHAR* argv[])
{
    Class x;
    cout << x.arr[2] << endl;
    return 0;
}

但我得到:
智能感知:数据成员的初始值是不允许的。

But i got: IntelliSense: data member initializer is not allowed

推荐答案

您需要在稍后进行初始化;你不能在类定义中初始化类成员。 (如果你可以,然后在头文件中定义的类会导致每个翻译单元定义自己成员的副本,使连接器与一个烂摊子理清。)

You need to perform the initialization later; you cannot initialize class members within the class definition. (If you could, then classes defined in header files would cause each translation unit to define their own copy of the member, leaving the linker with a mess to sort out.)

class Class {
  public:
      static string arr[];
};

string Class::arr[3] = {"one", "two", "three"};

类定义定义的接口的,它是独立于的实施

这篇关于C ++数据成员的初始值是不允许的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆