【问题标题】:Nested implicit conversion in C++C++ 中的嵌套隐式转换
【发布时间】:2013-07-04 06:32:48
【问题描述】:

我希望有两个级别的隐式转换。以下代码 sn-p 是我面临的问题的原型。

//Sources
class A
{
public:
    void print()
    {
        std::cout <<"Class A"<< std::endl;
    }

    operator int()
    {
        return 1;
    }
};

class B
{
public:
    void print()
    {
        std::cout <<"Class B"<< std::endl;
    }

    operator A()
    {
        return A();
    }
};

class C
{
public:
    void print()
    {
        std::cout <<"Class C"<< std::endl;
    }
    operator B()
    {
        return B();
    }
};


void print_(A a)
{
    a.print();
}

//driver

int main( int argc, char* argv[] )
{
    C c;

    //print_( c ); // compilation error
    //print_( C() ); // compilation error   
    print_( c.operator framework::configuration::B() ); //when explicitly invoked it worked 
    return 0;
}

我查看了以下链接中提供的示例,确信这是可以实现的。

How do conversion operators work in C++?

Operator overloading

【问题讨论】:

    标签: c++ implicit-conversion conversion-operator


    【解决方案1】:

    该标准只允许一种涉及用户定义类型的隐式转换。你有两个,因此编译错误。

    见 12.3/4

    最多一个用户定义的转换(构造函数或转换函数)被隐式应用于单个 价值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多