C++ 函数编译,即使它没有';不接受整数

C++ 函数编译,即使它没有';不接受整数,c++,class,oop,inheritance,C++,Class,Oop,Inheritance,当一个函数的参数只接受一个类型为敌方(void foo(const敌方&inKlep))的类时,我很困惑我们如何传递一个整数。 然而,当我们传递给它一个int(300)时,它会编译。这是为什么 #include <iostream> using namespace std; class Enemy { public: Enemy() { cout << "E ctor" << endl; } Enemy(int i) { cout << "E

当一个函数的参数只接受一个类型为敌方
(void foo(const敌方&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!
}
#包括
使用名称空间std;
阶级敌人{
公众:

Cube({Cuth

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
}

为什么你认为它不应该编译呢?
敌方(inti)
隐式转换…使它显式化,它就不会编译。所以说foo(7)就像说:foo(敌方(7))它会隐式创建一个,对吗?是的,如果你不想发生这种情况,当你定义一个接受单个参数的构造函数时(除了特殊的构造函数ofc),你应该添加
explicit
关键字。“compiles”并不意味着“按你的意图工作”,甚至“有任何定义良好的行为”.编译某些东西并不意味着你的程序是正确的,远远不是。
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
}