Initializing static array of strings (C++)?

我只是一个虾纸丫 提交于 2020-01-21 01:15:47

问题


I can't for the life of me figure out how to do this properly. I have a class that needs to store some constants (text that corresponds to values in an enum type) - I have it declared like this (publicly) in my class:

const static char* enumText[];

And I'm trying to initialize it like this:

const char* MyClass::enumText[] = { "A", "B", "C", "D", "E" };

However gcc gives me the following error:

'const char* MyClass::enumText[]' is not a static member of 'class MyClass'

What am I doing wrong? Thanks!


回答1:


This code compiles:

struct X {
   static const char* enumtext[];
};

const char* X::enumtext[] = { "A", "B", "C" };

Check your code and find differences. I can only think that you did not define the static attribute in the class, you forgot to include the header or you mistyped the name.




回答2:


This compiles with gcc version 4.0.1:

#include <iostream>

class MyClass {
public:
    const static char* enumText[];
};

const char* MyClass::enumText[] = { "a", "b", "c" };

int main()
{
    std::cout << MyClass::enumText[0] << std::endl;
}

Compiled with:

g++ -Wall -Wextra -pedantic s.cc -o s

Are you sure that MyClass::enumText is referencing the right class?




回答3:


Given the error message, it seems to me that you have a declaration of MyClass somewhere (in another header maybe?) that doesn't have enumText[] declared in it. The error message indicates that the compiler knows about MyClass, but it doesn't know about the enumText member.

I'd look to see if you have multiple declarations of MyClass lurking in the shadows.

Can you get wintermute's or T.E.D.'s examples to compile?




回答4:


As the compiler say, you're trying to define a static member of MyClass that would be a const char* array named enumText. If you don't have it's declaration in the class, then there is a problem.

You should have :

class MyClass
{
   //blah
   static const char* enumText[];
};

or maybe you didn't want a static member. If not, you shouldn't have to use a class in the name.

Anyway, that has nothing to do with array initialization.




回答5:


The following code compiles just fine for me in VS 2005:

class MyClass
{
const static char* MyClass::enumText[];
};
const char* MyClass::enumText[] = { "A", "B", "C", "D", "E" };

If I had to take a wild guess, I'd say that your initilization line is in a separate source file, and you forgot to #include the .h file that contains MyClass. That's exactly the kind of thing I screw up and do all the time.

Also, it seems quite likely to me that you have the const in the wrong spot (or not enough of them). The way you have it now, it isn't the array that is constant, or the pointers in the array; just the character elements within it.



来源:https://stackoverflow.com/questions/1376264/initializing-static-array-of-strings-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!