Reputation: 185
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"};
}
}
Here is what i have tried:
// 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
Upvotes: 12
Views: 29629
Reputation: 23619
You must initialize static members outside your class, as if it would be a global variable, like this:
class Class {
public:
static string arr[3];
};
string Class::arr = {"one", "two", "three"};
Upvotes: 2
Reputation: 26184
You have to initialize your static member outside of the class declaration:
string Class::arr[3] = {"one", "two", "three"};
Upvotes: 0
Reputation: 355069
Only static, integer-type data members may be initialized in the class definition. Your static data member is of type string
, so it cannot be initialized inline.
You must define arr
outside of the class definition, and initialize it there. You should remove the initializer from the declaration and the following after your class:
string Class::arr[3] = {"one", "two", "three"};
If your class is defined in a header file, its static data members should be defined in exactly one source (.cpp) file.
Also note that not all errors that appear in the Error List in Visual Studio are build errors. Notably, errors that begin with "IntelliSense:" are errors that IntelliSense has detected. IntelliSense and the compiler do not always agree.
Upvotes: 1
Reputation: 169018
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"};
The class definition defines the interface, which is separate from the implementation.
Upvotes: 18