gpt4 book ai didi

c++ - 调用初始化列表中的函数有没有问题?

转载 作者:可可西里 更新时间:2023-11-01 18:22:03 26 4
gpt4 key购买 nike

我正在写这个拷贝构造函数:

//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];
}
}
}

像这样在初始化列表中初始化numRow,numCol是不是有问题:numRow(other.numRow),numCol(other.numCol)而不是:

this-> numRow = other.getRow();
this-> numCol = other.getCol();

另外,不知道有没有这个问题,在初始化列表中调用其他类对象的函数有没有问题,比如:

numRow(other.getRow())

代替:

this-> numRow = other.getRow();

最佳答案

Is there a problem to initialize numRow, numCol in the initialization list [...]?

一般,这样做有两个问题:

  1. 正在初始化初始化列表中的对象时,对象尚未完全构建。因此,当您调用非静态成员函数时,您是在尚未完全构建的对象 上调用它们。如果这些函数试图使用尚未构造的对象的任何子对象,则您正在调用未定义的行为
  2. 初始化的顺序是成员在类定义中声明的顺序不是 它们在初始化列表 中的排列顺序。因此需要注意需要其他成员数据的成员初始化。 (这可以看作是前面的一个子问题:使用尚未构造的子对象。)最好避免这种情况,但如果无法避免,请在声明成员的地方添加一个大而可怕的注释在类的定义中,强调了它们顺序的重要性。

在您的具体示例中,这无关紧要,因此您可以安全执行此操作。

关于c++ - 调用初始化列表中的函数有没有问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3899555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com