C++中关于类型转换的问题
阿神
阿神 2017-04-17 15:25:18
0
2
437

C++ Primer上说,

struct B;
struct A{
         A()=default;
         A(const B&);
};
struct B{
         operator A() const;
}
A f(const A&);
B b;
A a=f(b);//二义性错误
A a1=f(b.operator A());//正确
A a2=f(A(b));//正确

我们无法使用强制类型转换来解决二义性问题,因为强制类型转换本身也面临二义性,这句话到底是什么意思啊?这不是通过强制类型转换实现了功能吗?

阿神
阿神

闭关修行中......

reply all(2)
阿神

What exactly does this sentence mean?

This sentence means: (There is ambiguity when calling f(b)) This ambiguity cannot be eliminated by using forced type conversion (f(static_cast<A>(b)) or f((A)b)). The original sentence is:

Note that we can’t resolve the ambiguity by using a cast—the cast
itself would have the same ambiguity.


Isn’t this function implemented through forced type conversion?

No, neither of the two correct calls in the example uses a cast. The first call removes ambiguity by explicitly calling B's conversion function, and the second call removes ambiguity by explicitly calling B's conversion function.

To put it simply, using cast type conversion here cannot eliminate the ambiguity of the call because the cast itself requires a feasible conversion sequence, but two can be obtained through the converting constructor and the conversion function respectively. Feasible conversion sequence, and there is no superiority or inferiority (?) between the two.


Not relevant:
But it seems doubtful whether there is any real ambiguity here.

黄舟

It means that C++ does not specify how to force conversion. It can choose either the constructor of A or the overload of B. Which one to choose and how to implement it is decided by the IDE itself. Different versions of IDE have different implementations.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template