简体   繁体   English

从int显式转换为用户定义的类c

[英]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? 我如何启用从int到用户定义的类Foo的显式转换?

I made a conversion constructor from int to Foo, but is that it? 我做了一个从int到Foo的转换构造函数,但这是吗? I could overload a cast operator from Foo to int, but that is not what I'm looking for. 我可以重载从Foo到int的强制转换运算符,但这不是我想要的。

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. 如果您不将构造函数设置为explicit ,则可以将类型(构造函数接受)转换为(新构造的)类实例。

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 您需要一个接受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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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