类初始化数组 [英] class initialized array

查看:72
本文介绍了类初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




如何在类构造函数中初始化const char * myarr []?

class Myclass {

const char * myarr [] = {" abc"," def" };

....

};

Myclass :: Myclass():

myarr [] (???)

{}


谢谢

Hi

how can I initialize a const char* myarr[] in a class constructor?

class Myclass {
const char* myarr[] = { "abc", "def" };
....
};
Myclass::Myclass():
myarr[]( ??? )
{}

thanks

推荐答案

Gary Wessle写道:
Gary Wessle wrote:

如何在类构造函数中初始化const char * myarr []?
how can I initialize a const char* myarr[] in a class constructor?



你不能。没人能。无法做到这一点。


V

-

请在回复e时删除资金'A' -mail

我没有回复最热门的回复,请不要问

You cannot. Nobody can. No way to do that.

V
--
Please remove capital ''A''s when replying by e-mail
I do not respond to top-posted replies, please don''t ask


你需要添加静态关键字。


class MyClass

{

public:


MyClass(){} < br $>
~MyClass(){}

static const char * myarr [];

};

const char * MyClass :: myarr [] = {" abc"," def" } <

You need to add the static keyword.

class MyClass
{
public:

MyClass(){}
~MyClass(){}

static const char * myarr[];
};

const char * MyClass::myarr[] = {"abc", "def" };


Gary Wessle写道:
Gary Wessle wrote:

如何初始化const char * myarr []在类构造函数中?

class Myclass {

const char * myarr [] = {" abc"," def" };

...

};


Myclass :: Myclass():

myarr [](???)

{}
how can I initialize a const char* myarr[] in a class constructor?

class Myclass {
const char* myarr[] = { "abc", "def" };
...
};
Myclass::Myclass():
myarr[]( ??? )
{}



使用字符串向量而不是char指针数组

http:// www.parashift.com/c++-faq-lit...html#faq-34.1) ,然后

然后使用初始化助手类:


模板< typename T>

类初始化程序

{

vector< Tv_;

public:

初始值设定项(size_t reserveSize = 0){v_.reserve(reserveSize); }

初始化器&添加(const T& t){v_.push_back(t);返回*这个; }

运算符向量< T>()const {return v _; }

};


class Myclass {

const vector< stringmyarr;

public:

Myclass()

:myarr(初始化器(2)

.Add(" abc")

。添加(def))

{}

};


干杯! --M

Use a vector of strings rather than an array of char pointers
(http://www.parashift.com/c++-faq-lit...html#faq-34.1), and
then use an initializer helper class:

template<typename T>
class Initializer
{
vector<Tv_;
public:
Initializer( size_t reserveSize=0 ) { v_.reserve( reserveSize ); }
Initializer& Add( const T& t ) { v_.push_back(t); return *this; }
operator vector<T>() const { return v_; }
};

class Myclass {
const vector<stringmyarr;
public:
Myclass()
: myarr( Initializer( 2 )
.Add( "abc" )
.Add( "def" ) )
{}
};

Cheers! --M


这篇关于类初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆