怎么用构造函数初始化类中数组数据成员
如何用构造函数初始化类中数组数据成员
#include "stdafx.h"
#include "iostream.h"
#define M 2
#define N 3
class complex{
private:
int a[M][N];
public:
complex(int b[2][N])
{a=b;
}
complex operator+(complex c)
{int i,j;
complex temp;
for(i=0;i<M;i++)
for(j=0;j<N;j++)
temp.a[i][j]=a[i][j]+c.a[i][j];
return temp;
}
void print()
{int i,j;
for(i=0;i<M;i++)
{for(j=0;j<N;j++)
cout<<a[i][j]<<' ';
cout<<endl;
}
}
};
int main(int argc, char* argv[])
{int a[M][N]={{1,2,3},{4,5,6}};
int b[M][N]={{7,8,9},{10,11,12}};
complex A1(a);
complex A2(b);
complex A3;
A1.print();
A2.print();
A3=A1+A2;
A3.print();
return 0;
}
调试时出现如下问题:D:\c++\4\4.cpp(12) : error C2440: '=' : cannot convert from 'int [][3]' to 'int [2][3]'
There are no conversions to array types, although there are conversions to references or pointers to arrays
D:\c++\4\4.cpp(17) : error C2512: 'complex' : no appropriate default constructor available
D:\c++\4\4.cpp(37) : error C2512: 'complex' : no appropriate default constructor available
谢谢啊,呵呵。
------解决方案--------------------
complex(int b[2][N])
{a=b;
}
这个不行,得一一覆值
------解决方案--------------------
数组不能整体拷贝,这是最基本的C语言常识了。
------解决方案--------------------
complex(int b[2][N])
{a=b;
}
数组不能直接赋值。。
一个一个复制吧
#include "stdafx.h"
#include "iostream.h"
#define M 2
#define N 3
class complex{
private:
int a[M][N];
public:
complex(int b[2][N])
{a=b;
}
complex operator+(complex c)
{int i,j;
complex temp;
for(i=0;i<M;i++)
for(j=0;j<N;j++)
temp.a[i][j]=a[i][j]+c.a[i][j];
return temp;
}
void print()
{int i,j;
for(i=0;i<M;i++)
{for(j=0;j<N;j++)
cout<<a[i][j]<<' ';
cout<<endl;
}
}
};
int main(int argc, char* argv[])
{int a[M][N]={{1,2,3},{4,5,6}};
int b[M][N]={{7,8,9},{10,11,12}};
complex A1(a);
complex A2(b);
complex A3;
A1.print();
A2.print();
A3=A1+A2;
A3.print();
return 0;
}
调试时出现如下问题:D:\c++\4\4.cpp(12) : error C2440: '=' : cannot convert from 'int [][3]' to 'int [2][3]'
There are no conversions to array types, although there are conversions to references or pointers to arrays
D:\c++\4\4.cpp(17) : error C2512: 'complex' : no appropriate default constructor available
D:\c++\4\4.cpp(37) : error C2512: 'complex' : no appropriate default constructor available
谢谢啊,呵呵。
------解决方案--------------------
complex(int b[2][N])
{a=b;
}
这个不行,得一一覆值
------解决方案--------------------
数组不能整体拷贝,这是最基本的C语言常识了。
------解决方案--------------------
complex(int b[2][N])
{a=b;
}
数组不能直接赋值。。
一个一个复制吧