简体   繁体   中英

Explicit cast from int to a user defined class, c++

How can I enable explicit casting from, lets say int, to a user defined class Foo?

I made a conversion constructor from int to Foo, but is that it? I could overload a cast operator from Foo to int, but that is not what I'm looking for.

Is there a way to enable this piece of code?

int i = 5;
Foo foo = (Foo)i;

Read about converting constructor .

If you won't set constructor as explicit , it allows you to convert type (which constuctor accepts) to a (newly constructed) class instance.

Here is the example

#include <iostream>

template<typename T>
class Foo
{
private:
    T m_t;
public:
    Foo(T t) : m_t(t) {}
};

int main()
{
    int i = 0;
    Foo<int> intFoo = i;

    double d = 0.0;
    Foo<double> doubleFoo = d;
}

Something like this:

struct Foo {
    explicit Foo(int x) : s(x) { }
    int s;
};
int main() {
    int i = 5;
    Foo foo =(Foo)i;
}

You need a constructor which accecpts an int

class Foo {

  public:
     Foo (int pInt) {
        ....
     }
     Foo (double pDouble) {
        ....
     }


int i = 5;
Foo foo(i);  // explicit constructors
Foo foo2(27);
Foo foo3(2.9);

Foo foo4 = i;  // implicit constructors
Foo foo5 = 27;
Foo foo6 = 2.1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM