相关疑难解决方法(0)

可以使用成员变量初始化初始化列表中的其他成员吗?

考虑以下(简化)情况:

class Foo
{
private:
    int evenA;
    int evenB;
    int evenSum;
public:
    Foo(int a, int b) : evenA(a-(a%2)), evenB(b-(b%2)), evenSum(evenA+evenB)
    {
    }
};
Run Code Online (Sandbox Code Playgroud)

当我像这样实现Foo时:

Foo foo(1,3);
Run Code Online (Sandbox Code Playgroud)

然后evenA是0,evenB是2,但是甚至将初始化为2?

我在我当前的平台(iOS)上尝试了这个,它似乎工作,但我不确定这段代码是否可移植.

谢谢你的帮助!

c++ initialization-list member-variables

30
推荐指数
3
解决办法
3779
查看次数

在初始化列表中调用函数有什么问题吗?

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

//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)

c++ initialization

7
推荐指数
2
解决办法
5730
查看次数

在构造函数中使用setter

我是一名试图学习C++的Java开发人员.是否可以在构造函数中使用setter以重用setter提供的健全性检查?

例如:

#include <stdexcept>
using namespace std;

class Test {
    private:
        int foo;
        void setFoo(int foo) {
            if (foo < 42) {
                throw invalid_argument{"Foo < 42."};
            }

            this->foo = foo;
        }

    public:
        Test(int foo) {
            setFoo(foo);
        };
};
Run Code Online (Sandbox Code Playgroud)

c++ setter constructor

5
推荐指数
1
解决办法
2273
查看次数