避免在构造函数中进行隐式转换。 'explicit'关键字在这里没有帮助 [英] Avoiding implicit conversion in constructor. The 'explicit' keyword doesn't help here

查看:83
本文介绍了避免在构造函数中进行隐式转换。 'explicit'关键字在这里没有帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 explicit 关键字避免构造函数的隐式转换。因此,现在可以避免像 A a1 = 10; 这样的转换。

I am able to avoid the implicit conversion of a constructor using the explicit keyword. So now, conversions like A a1 = 10; can be avoided.

但是我仍然可以初始化 A a1 = A(20.2); 。如何禁用对象创建,以便仅当我们将整数作为参数传递时才能创建对象。 A a1 = A(10)

But still I can initialize A a1 = A(20.2);. How can I disable the object creation such that an object can only be created if we pass an integer as a parameter e.g. A a1 = A(10)?

#include <iostream>

class A
{
public:
    explicit A(int a)
    {
        num = a;
    }

    int num;
};

int main()
{
    A a1 = A(10.0);
    std::cout << a1.num;
    return 0;
}


推荐答案

您可以删除 A :: A(<任何不是int>);;

struct A
{
    explicit A(int a)
    : num(a)
    {}

    template<class T>
    A(T) = delete;

    int num;
};

int main()
{
    //A a1=A(10.0); // error: use of deleted function 'A::A(T) [with T = double]'
    A a2 = A(10); // OK
    (void) a2;
}

演示: https://coliru.stacked-crooked.com/a/425afc19003697c9

这篇关于避免在构造函数中进行隐式转换。 'explicit'关键字在这里没有帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆