【问题标题】:what will the equivalent statement of line in main?main 中 line 的等效语句是什么?
【发布时间】:2020-02-19 16:36:01
【问题描述】:
class B{
    float floatVar;
    public:
    B(float a):floatVar(0.0){
        floatVar = a;
    }

    operator int(){   // Consider this as line A
        return floatVar;
    }
};


int main()
{
    B floatObj(5.5);    
    cout << floatObj;  // Consider this as line B

    return 0;
}

当我重载 int() 时 cout 显示 5,当我在 A 行中将 int() 替换为 float() 时,程序显示 5.5。 我想知道它是如何自动调用 cout 中的 int() typecaster 或 float() 的?

【问题讨论】:

  • 在重载解析中找到std::ostream::operator&lt;&lt;,并且它具有采用floatint 等的重载,因此尝试从floatObj 到每个重载的隐式转换。 en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt
  • @M.M 我又添加了一个数据成员,但现在它不起作用?发生了什么事?
  • 等一下,让我找到我的水晶球

标签: c++


【解决方案1】:

C++ 中没有默认的printing 函数或类似函数的综合,因此如果您尝试打印类的对象,则默认情况下定义具有某些字段的类不会打印它们。 p>

由于您没有定义任何重载运算符 &lt;&lt; 以打印到某些 ostream(如 cout),因此编译器找到了一种通过定义的转换为 int 来打印它的方法。

【讨论】:

    【解决方案2】:

    在搜索匹配的函数重载时,允许编译器隐式执行一次用户定义的转换。由于您提供了从Bint 的转换,编译器可以使用它并为std::cout 选择&lt;&lt; 运算符的operator &lt;&lt;(std::ostream, int) 重载。


    如果您要向operator &lt;&lt; 接受的std::ostream 类型(例如float)添加另一个转换,编译器会说这是模棱两可的调用,它不能自行选择。

    class B{
        float floatVar;
        public:
        B(float a):floatVar(0.0){
            floatVar = a;
        }
    
        operator int(){
            return floatVar;
        }
        operator float(){   
            return floatVar;
        }
    };
    
    
    int main()
    {
        B floatObj(5.5);    
        cout << floatObj;  //error: ambiguous overload for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'B')
    
        cout << static_cast<int>(floatObj); //explicit conversion, compiles
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多