【发布时间】:2023-04-08 13:33:01
【问题描述】:
我已经设法重载了赋值运算符,所以我确实有一个解决方法,但很高兴知道为什么我不能让它工作。
我的 arr2d 类的开头如下所示:
template <class type> class arr2d {
private:
type* m_ptr;
int m_nx,m_ny;
public:
arr2d(){
m_ptr = 0;
m_nx = 0;
m_ny = 0;
}
// Default constructor creates a null array
arr2d(int nx, int ny):m_nx(nx),m_ny(ny){
m_ptr = new type [nx*ny];
if ( m_ptr==0 ){cout << "\nError allocating heap memory.\n";}
}
// // Copy constructor
// arr2d(const arr2d& rhs){
// m_ptr = new type [m_nx*m_ny];
// for(int j=0;j<m_ny;j++){
// for(int i=0;i<m_nx;i++){
// m_ptr[j*m_nx+i] = rhs.m_ptr[j*m_nx+i];
// }
// }
// }
等等,
你可以看到我尝试的复制构造函数被注释掉了。
现在在我的主目录中,我想调用复制构造函数,例如:
arr2d b=a;
b 数组现在与 a 具有相同的值。我做错了什么?
【问题讨论】:
-
可能与您的问题无关,但最好遵循 Big 3 规则。en.wikipedia.org/wiki/Rule_of_three_(C++_programming)
标签: c++ arrays pointers constructor copy