当显式转换是必需的并且隐式转换将不起作用时

when explicit conversion is necessary and implicit will not work

本文关键字:转换 不起作用 显式转换      更新时间:2023-10-16

当我有 2 个具有实现转换构造函数和转换运算符的类时,是否有可能需要显式转换的情况,因为隐式不起作用?(我用 2 个类做例子,看看继承是否有任何区别)

当可以隐式应用多个转换时,为了解决歧义,可能需要显式转换:

#include <iostream>
using namespace std;
void f(double x) {
    cout << "Doublen";
}
void f(int x) {
    cout << "Integern";
}
struct C
{
    C(float x) { this->x = x; }
    operator int() { return (int)x; }
    operator double() { return (double)x; }
    float x;
};
int main(int argc, char* argv[]) 
{
    C c(1);
    f(c); // error C2668: 'f' : ambiguous call to overloaded function
    f(static_cast<double>(c)); // calls f(double)
    f(static_cast<int>(c)); // calls f(int)
}
下面是

一个继承示例,其中显式类型转换是必需的:

// Base class.
class Foo
{
};
// Derived class.
class Bar : public Foo
{
public:
    void SomeMethod()
    {
        cout << "I a in Bar!" << endl;      
    }
};
// Global method; input argument is derived class pointer.
void method(Bar* obj)
{
    obj->SomeMethod();
}
// main
int main()
{
    Foo* obj1 = new Foo();
    method(obj1); // This line will error when passing the base class object
                  // error C2664: 'method' : 
                  //cannot convert parameter 1 from 'Foo *' to 'Bar *'

    return 0;
}

所以这里你需要显式类型转换为派生类。

method((Bar*) obj1);

希望这有帮助。

只要你有相关的构造函数

class A
{
  // ...
  A(const B& b);  // or similar
};

类型的隐式强制转换

B b(...);  // B is the other class
A a = b;

B b(...);
A a(b);

会工作。