Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

c++ - warning #411: class foo defines no constructor to initialize the following:

I have some legacy code built with c++ compiler giving the error in the subject line

typedef struct foo {
    char const * const str;
 } Foo;

and a lot of places in the code (meaning I cannot change all of them) use it in a C style initialization:

 Foo arr[] ={
     {"death"},
     {"turture"},
     {"kill"}
  }

What is the good workaround to remove the stupid warning?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't modify the const pointer after construction. You need a constructor initializer to initialize 'str'.

struct Foo
{
  const char* const str;
  explicit Foo(const char* str_) : str(str_) {}
};

Note that 'typedef' is not required in C++ for a case like this.

EDIT:

If you can't use a constructor, then you must make your pointer non-const:

struct Foo
{
  const char* str;
};

ANOTHER EDIT:

After litb's comment, I tried the original code and it does indeed compile (g++ 4.1.2 and XL C/C++ 8.0) with no warnings. Perhaps the compiler in question is doing a construction followed by assignment in this case? I used less violent strings, but I doubt that would make a difference. ;v)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...