我正在写这个拷贝构造函数:
//CCtor of RegMatrix
RegMatrix::RegMatrix(const RegMatrix &other){
this-> numRow = other.getRow();
this-> numCol = other.getCol();
//Create
_matrix = createMatrix(other.numRow,other.numCol);
int i,j;
//Copy Matrix
for(i=0;i<numRow; ++i){
for(j=0;j<numCol; ++j){
_matrix[i][j] = other._matrix[i][j];
}
}
}
Run Code Online (Sandbox Code Playgroud)
在初始化列表中初始化numRow,numCol是否有问题,如下所示:numRow(other.numRow), numCol(other.numCol)
而不是:
this-> numRow = other.getRow();
this-> numCol = other.getCol();
Run Code Online (Sandbox Code Playgroud)
另外,我不知道是否存在这样的问题,是否存在在初始化列表中调用其他类的对象函数的问题,例如:
numRow(other.getRow())
Run Code Online (Sandbox Code Playgroud)
代替:
this-> numRow = other.getRow();
Run Code Online (Sandbox Code Playgroud) 假设我想要一个接收一些参数的构造函数,并且使用这些参数我可以计算它的成员变量的值.除了成员变量的值不是参数的简单赋值.它们需要创建其他对象并转换值,然后才能将它们用作成员变量的值.
这是填充初始化列表的方法.由于无法创建变量并重复使用它们,因此您必须复制代码(并生成同一对象的多个副本)以适合初始化列表中的所有代码,因此效率也非常低.
另一个选项是不使用初始化列表并让默认构造函数被调用,然后用整齐的计算覆盖构造函数内的值.
现在如果该类没有默认构造函数怎么办?怎么能整齐地做到这一点?
/* a class without a default constructor */
class A {
public:
B x1
B x2
A(B x1_, B x2_) : x1{x1_}, x2{x2_} {};
};
/* a class that contains an A object and needs to initialize it based on some complex logic */
class C {
public:
A a;
C(D d) :
a{b1,b2} // ultimately I just want to initialize a with two B objects
// but unfortunatelly they require a lot of work to …Run Code Online (Sandbox Code Playgroud)