如何在成员初始化列表中为const char*
类成员分配内存?
class A {
const char *member;
public:
A(const char *m);
}
A::A(const char *m):member(m) {
//I want to allocate memory to member in member initialization list
}
答案 0 :(得分:0)
尝试以下
class A
{
const char *member;
public:
A(const char *m);
};
A::A(const char *m) : member( new char[std::strlen( m ) + 1] )
{
std::strcpy( member, m );
}
考虑到数据成员member
本身不是常量。
或者你甚至可以写下面的方式
#include <iostream>
#include <cstring>
struct A
{
const char *s;
A( const char *s ) : s( std::strcpy( new char[std::strlen( s ) + 1], s ) )
{
}
~A()
{
delete [] s;
}
};
int main()
{
A a( "Hello, World!" );
std::cout << a.s << std::endl;
return 0;
}