初始化列表中调用函数有问题吗? [英] Is there any problem of calling functions in the initialization list?

查看:15
本文介绍了初始化列表中调用函数有问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing this copy constructor:

//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)而不是:

Is there a problem to initialize numRow, numCol in the initialization list like this: numRow(other.numRow), numCol(other.numCol) instead of:

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

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

Also, i don't know if there isn't such a problem, is there a problem of calling other classes' object's function in the initialization list, such as:

numRow(other.getRow())

代替:

this-> numRow = other.getRow();

推荐答案

初始化列表中的numRow、numCol是否有问题[...]?

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

总的来说,这样做有两个问题:

In general, there's two problems with doing so:

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

在您的具体示例中,这并不重要,因此您可以安全执行此操作.

In your concrete example this doesn't matter, so you are safe to do this.

这篇关于初始化列表中调用函数有问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆