我谈给类成员数组进行大批赋值的方法

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 mahongxi 的 blog

今天上qq,有一个朋友问我怎么样给一个类的成员变量[是数组]赋初值。
比如:
class ctest
{private:
 int m_arr[10];
 ……
};

如果想给成员m_arr[]数组赋初值,怎么办呢?

我试过
ctest():m_arr({1,2,3,4……})
编译通过不了,出现错误:
cannot specify explicit initializer for arrays
不能给数组指定明显的初始化。

我然后告诉他试试在构造函数内部赋值,他说
如果这样
ctest()
{
 m_arr[0] =
 m_arr[1] =
……
}
太烦了。
如果
ctest()
{
 m_arr = {1,24,44,……};
}
又编译不了。

我想了一下,就采用了这个办法:

#include <conio.h>
#include <stdio.h>
#include <iostream.h>
#include <string.h>
#include <afxwin.h>

class ctest
{
private:
 int m_arr[10];
public:
 ctest()
 {
  int temparr[10] = {1,2,3,4,6,6,7,5,8,2};
  memcpy(m_arr,temparr,sizeof(temparr));
 }
 void disp()
 {
  for(int i = 0;i<10;i++)
  {
   cout<<"m_arr["<<i<<"]="<<m_arr[i]<<endl;
  }
 }
};

void main(void)
{
 ctest t;
 t.disp();
}

 


结果编译通过,结果正确。

不知大家遇到这种情况时,如何处理?

本文关键:数据成员 数组 赋值 memcpy
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top