OOP:将原始类型传递给期望对象的函数

时间:2021-08-28 05:27:42

Is it possible to pass constructor arguments to a function instead of the class object itself ?

是否可以将构造函数参数传递给函数而不是类对象本身?

According to the following code

根据以下代码

    #include <iostream>
    #include <string>


    class CL{
     public:
         int id;
       CL(){ 
           std::cout << "CL () Constructor "  << std::endl;
       }
       CL(const char * name){ 
           std::cout << " CL(const char * name) Constructor  Called " << std::endl;
       }
       CL(int i){ 
           id = i;
           std::cout << "CL(int i) Constructor  Called " << id << std::endl;

       }

       void print(){
           std::cout << "print method Called " << id << std::endl;
       }
    };

    void myfunc(CL pp){
        pp.print();
    }

    int main(int argc,char **argv){
        myfunc(10);
    }

I passed integer to the function "myfunc" instead of class instance and it worked. I think it instantiated object on the fly.

我将整数传递给函数“myfunc”而不是类实例,它工作正常。我认为它实时实例化了对象。

the output is

输出是

CL(int i) Constructor  Called 10
print method Called 10

is it such an ambiguity ? as for the same code if I overloaded the function "myfunc" as

它是如此含糊不清吗?至于相同的代码,如果我重载函数“myfunc”为

myfunc(int i) {
    std::cout << i << std::endl;
}

it will output 10

它会输出10

and ignore the function prototype that takes the class object

并忽略获取类对象的函数原型

1 个解决方案

#1


3  

This is called implicit conversion and works for all constructors, that take a single parameter. In cases, where you don't want that, declare the constructor explicit:

这称为隐式转换,适用于采用单个参数的所有构造函数。如果您不希望这样,请将构造函数声明为:

class CL {
 public:
   int id;

   CL(): id{0} {}
   explicit CL(int i): id{i} {}
};

void myfunc(CL pp) {
    // ... 
}

int main(int, char) {
    myfunc(10); // <- will fail to compile
}

#1


3  

This is called implicit conversion and works for all constructors, that take a single parameter. In cases, where you don't want that, declare the constructor explicit:

这称为隐式转换,适用于采用单个参数的所有构造函数。如果您不希望这样,请将构造函数声明为:

class CL {
 public:
   int id;

   CL(): id{0} {}
   explicit CL(int i): id{i} {}
};

void myfunc(CL pp) {
    // ... 
}

int main(int, char) {
    myfunc(10); // <- will fail to compile
}