考虑以下(简化)情况:
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)上尝试了这个,它似乎工作,但我不确定这段代码是否可移植.
谢谢你的帮助!
我正在写这个拷贝构造函数:
//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++的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)