【发布时间】:2019-05-10 19:02:51
【问题描述】:
我很困惑,当函数的参数只接受类型为敌人( void foo(const Enemy& inKlep ) 的类时,我们怎么能传递一个整数。
然而,当我们将 int (300) 传递给它时,它会编译。这是为什么呢?
#include <iostream>
using namespace std;
class Enemy {
public:
Enemy() { cout << "E ctor" << endl; }
Enemy(int i) { cout << "E ctor " << i << endl; }
Enemy(const Enemy& src) {cout << "E copy ctor"<< endl;}
Enemy& operator=(const Enemy& rhs) {cout<<"E="<<endl;}
virtual ~Enemy() { cout << "E dtor" << endl; }
void hornet(int i=7) const { // Not virtual!
cout << "E::hornet " << i << endl;
}
};
class Scott : public Enemy {
public:
Scott() : Enemy(1) { cout << "S ctor" << endl; }
Scott& operator=(const Scott& rhs) {cout<<"S="<<endl;}
virtual ~Scott() { cout << "S dtor" << endl; }
void hornet(int i=7) const {
cout<<"S::hornet " << i << endl;
}
};
void foo(const Enemy& inKlep) {
Enemy theEnemy;
inKlep.hornet(2);
}
int main(int argc, char** argv) {
foo(300);
cout << "Done!" << endl; // Don't forget me!
}
【问题讨论】:
-
为什么你认为它不应该编译?
-
Enemy(int i)隐式转换 ... 使那个 ctorexplicit并且它不会编译。 -
所以说 foo(7) 就像说 : foo(enemy(7) ) 因为它会隐式创建一个权利?
-
是的,如果你不希望这种情况发生,你应该在定义一个接受单个参数的构造函数时添加
explicit关键字(除了c的特殊构造函数) -
"compiles" not 是否意味着“按您的预期工作”甚至“完全有任何明确定义的行为”。仅仅因为某些东西可以编译并不意味着你的程序是正确的; 远离。
标签: c++ class oop inheritance