函数编译,即使它不接受整数

时间:2019-05-10 19:02:52

标签: c++ class oop inheritance

我很困惑,当函数的参数仅接受类型为( 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!
}

1 个答案:

答案 0 :(得分:3)

在C ++中,如果函数期望可以从该参数构造对象,则对于输入参数隐式构造对象是有效的代码。因此,例如:

struct CustomInt {
    int val;
    CustomInt() : CustomInt(0) {}
    CustomInt(int value) : val(value) {}
};

void func(CustomInt obj) {
    std::cout << obj.val << std::endl;
}

int main() {
    func(5); //Valid; will print '5' to the console
}

如果您不想允许这样做,则需要在构造函数中添加关键字explicit以防止这种情况。

struct CustomInt {
    int val;
    CustomInt() : CustomInt(0) {}
    explicit CustomInt(int value) : val(value) {}
};

void func(CustomInt obj) {
    std::cout << obj.val << std::endl;
}

int main() {
    //func(5); //Invalid; will cause a compile-time error
    func(CustomInt(5)); //Valid; will print '5' to the console
}