Gary Wessle wrote:
Hi
how can I initialize a const char* myarr[] in a class constructor?
class Myclass {
const char* myarr[] = { "abc", "def" };
...
};
Myclass::Myclas s():
myarr[]( ??? )
{}
thanks
You could deal with allocating a pointer in the ctor body.
But thats old school stuff and frankly: much more work and way too
fragile.
You can only initialize an array with default values.
example:
template< typename T, const size_t Size >
MyClass
{
T array[ Size ];
MyClass() : array() { } // init elements to
// whatever the default T() might be
};
A std::string doesn't suffer from that handicap.
#include <iostream>
#include <ostream>
#include <string>
template < typename T >
class MyClass
{
T m_t;
public:
MyClass(const T& t) : m_t(t) { }
friend
std::ostream&
operator<<(std: :ostream& os, const MyClass& r_my)
{
return os << r_my.m_t;
}
};
int main()
{
MyClass< std::string instance("abc def");
std::cout << instance << std::endl; // so simple
return 0;
}