Re: How to initialize an array of class?
- From: "Tom Widmer [VC++ MVP]" <tom_usenet@xxxxxxxxxxx>
- Date: Mon, 17 Oct 2005 12:30:13 +0100
zhanglr wrote:
Hi,
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
{
}
private:
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
{
}Tom .
- Follow-Ups:
- Re: How to initialize an array of class?
- From: zhanglr
- Re: How to initialize an array of class?
- References:
- How to initialize an array of class?
- From: zhanglr
- How to initialize an array of class?
- Prev by Date: Re: SFINAE compiler problem?
- Next by Date: Re: Using a C++ dll by both a Powerbuilder app and a C++ app
- Previous by thread: Re: How to initialize an array of class?
- Next by thread: Re: How to initialize an array of class?
- Index(es):
Relevant Pages
|