Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 引用类型之间的隐式转换_C++_Type Conversion - Fatal编程技术网

C++ 引用类型之间的隐式转换

C++ 引用类型之间的隐式转换,c++,type-conversion,C++,Type Conversion,给定两个具有相同数据布局的类A和B(即只有函数不同,而不是成员不同),如何使引用类型隐式可转换 struct Storage { uint32_t a, b; }; class First : private Storage { int32_t GetA() { return a; } int32_t GetB() { return b; } }; class Second : private Storage { int64_t GetA() { retur

给定两个具有相同数据布局的类A和B(即只有函数不同,而不是成员不同),如何使引用类型隐式可转换

struct Storage
{
    uint32_t a, b;
};


class First : private Storage
{
    int32_t GetA() { return a; }
    int32_t GetB() { return b; }
};

class Second : private Storage
{
    int64_t GetA() { return a; }
    int64_t GetB() { return b; }
};


void FuncF(const First& first);
void FuncS(const Second& second);    

// I would like to be able to call like
int main()
{
    First f;
    Second s;

    FuncF(s);          // Conversion fails
    FuncS(f);          // Conversion fails

    return 0;
}
我可以通过passby copy实现上面的工作,如果我使用继承,比如
类First:Second
我可以通过一种方式实现转换

(请注意,上面是一个人为的示例,您可以想象int32_t和int64_t返回类型是可以从uint32_t构造的更复杂的类)

明确地说:我对变通方法不感兴趣,我特别希望能够将
第一个
对象绑定到
第二个
引用,反之亦然,这取决于数据是相同的事实

FuncS(static_cast<Second&>(f));   // This works, is it standard (ie portable) 
                                  // and can I define the class so the cast is not necessary?
FuncS(static_cast(f));//这行得通,是标准的吗(即便携的)
//我可以定义类,这样就不需要强制转换了吗?
您可以使用

所以Second需要一个如下形式的成员函数:Second::operator First();
同样的,在第一次。这将执行隐式转换,而无需类型转换。

您可以将继承公开,然后两种类型的值都可以绑定到对基的引用。