开发者

char array compilation error

开发者 https://www.devze.com 2023-03-16 09:00 出处:网络
What is the problem in my code? It does not compile.. class FileNames { public: static char* dir; static char name[100];

What is the problem in my code? It does not compile..

   class FileNames
   {
        public:
           static char* dir;
           static char name[100];

   开发者_StackOverflow社区        static void Init3D()
           {
            FileNames::dir = "C://3D//";
            FileNames::name = "abc";
           }
   };   


You cannot assign to an array, so FileNames::name = "abc" fails (char arr[4] = "abc" works, however, because this is a direct initialization, not assignment). Either use a char* here as well, or use strcpy to copy data to the array or better a std::string which avoids many of the downsides of raw strings.

Most importantly you need to define your static members somewhere at global scope, outside a function: char FileNames::name[100];. At this time initialization syntax using = would be possible even with the array, but the string to be assigned needs to have the same length as the array.


There are two problems with your code:

1) You've duplicated the variable name (with two different types).
2) You can't initialise static members like that (see example below).

The last thing isn't a problem as such, but you should consider using std::string instead, as that encapsulates string functionality so that you don't need to deal with raw pointers. It's a lot less painful, especially if you're new to this sort of thing.

Change it to this:

// Header file
class FileNames
{
private:
    static char* name;
public:
    static char* dir;
};

CPP file
#include "FileNames.h"

char* FileNames::name = "abc";
char* FileNames::dir = "C://3D//";

// Now use your class...


Try initializing like this:

class FileNames
{
    public:
       static char* dir;
       static char name[];

};   

char *FileNames::dir = "C://3D//";
char FileNames::name[100] = "abc";


Did you remember to actually define the static members outside of the class? Also, I don't believe you need to resolve the scope unless you're actually outside of the class.


Use:

FileNames::dir = new char[strlen("C://3D//")];
strcpy(FileNames::dir, "C://3D//");
strcpy(FileNames::name, "abc");

Also, don't forget to #include <cstring> and to later delete[](FileNames::dir)

0

精彩评论

暂无评论...
验证码 换一张
取 消