Re: How to initialize an array of class?

zhanglr wrote:

Is it possible to initialize an array of class which don't provide a no-arg constructor?

I just write few lines code to explain what I want.

I have a class call _CString. (I will use it as a sealed class. so I can create and use an array of _CString.) and "_CString arstr[10]" is a member variable of CStrArray.

I hope to initialize arstr at CStrArray's constructor like "CStrArray( const char* arpch[10] ): arstr(arpch){};" but it failed. So I have to provide "_CString()" and "void SetData(const char* pch)"

Yes, you can't copy arrays.

I don't really appreciate this way. But I don't know what I can do to solve this kind of problem. or what is the normal way to handle this kind of issue (convert an input array in c style, e.g. const char*[], to c++ style array e.g. _CString[] or _CString&[])?

Generally you have to copy the values one by one, but the best alternative is to use a templated container class, like std::vector.

#include <string>
#include <vector>

class CStrArray
  CStrArray( const char* arpch[10] )
    :arstr(arpch, arpch + 10) //initialize from range
  typedef std::vector<std::string> arstr_t;
  arstr_t arstr;

And that's it. You can even work with arbitrary lengths:
  template <int N>
  CStrArray( const char* arpch[N] )
    :arstr(arpch, arpch + N) //initialize from range


Relevant Pages

  • Re: Controlling Static Data and Memory Organization...If Possible...
    ...   int value; ... with each successive entry into the static array. ... compilers and compiler options. ... const char name; ...
  • Re: why is this assignment correct ?
    ... The C standard specifies that the type of a string literal is "array ... of char" and most specifically not "array of const char". ... to modify a string literal in C produces undefined behavior, ...
  • Re: About Segmentation fault
    ... It's perfectly legal to modify non-constant array elements. ... Like all string literals in C, ... I never said "array of 6 const char". ...
  • Re: Is C++ a type-safe language ??
    ... The conversion of this array or const char to char* is explicitly allowed ... One excemption from type safety rules for the purpose of bacwards ... compatibility does not make C++ a non-type safe language. ...
  • Re: Why is "Hello World" const char* ?
    ... > Your statement is incorrect. ... Since the first character is of type (const char) as ... > pointer to const char. ... The type of a string literal is "array of char", ...