class Act {
protected:
string Owner;
double Balance;
public:
explicit Act(int = 0);
double getBalance() { return Balance; };
};
构造函数行 Act(int =0); 的含义是什么?需要 int=0 在这里做什么。
最佳答案
解释
explicit Act (int = 0);
定义一个构造函数,它从一个int
参数构造一个Act
。 =0
表示如果参数可以省略,则默认值为 0。explicit
关键字告诉编译器不要使用此构造函数来生成隐式转换。
使用示例
原样:
Act a1; // Will generate the same code as Act a1(0);
Act a5{}; // Same as above, but using the braced initialization
Act a2(12); // Obvious
Act a3=13; // Ouch ! Compiler error because of explicit
Act a4 = Act(13); // Ok, because now the call is explicit
如果你没有明确的关键字,那么这一行就可以了
Act a3=13; // If not explicit, this is the same than Act a3=Act(13);
重要说明
默认值不是构造函数本身的一部分,而是基于调用方已知的构造函数声明在调用方定义的行为。
这意味着您可以在不同的编译单元中包含声明具有不同默认值的类。尽管很奇怪,但这是完全正确的。
注意,声明中没有参数名也不是问题,因为,参数名可以在构造函数定义中声明:
Act::Act(int x) : Balance((double)x) {
cout <<"Constructor Act with parameter "<<x<<endl;
}
最后,请注意,如果您想通过省略参数来使用默认值,但您的构造函数只有一个参数,则您应该使用上面示例中的语法形式 a1 或 a5。但是,您不应使用带空括号的语法,因为这会被理解为函数声明:
Act a0(); // Ouch !! function declaration ! Use a0 or a0{} instead.
关于带有声明帐户的 C++ 构造函数(int =0);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47603020/