C++ Setter/Getter,cout 有效,printf 失败

C++ Setter/Getter, cout works, printf fails

有人知道为什么 C++ 在可变参数 printf 函数上失败吗?代码可以修复吗?这只是一个简单的例子,但一般情况对我来说很重要。

#include <stdio.h>
#include <iostream>

using namespace std;

class Float32 {
    public:
        float & operator = (const float &newValue) {
            return value = newValue;
        }
        operator float () const {
            return value;
        }
    protected:
        float value;
};

int main() {
    Float32 value;
    value = 0.5;

    cout << "cout value: " << value << endl; // this works
    printf("something fishy about varargs or something...\n");

    printf("printf value: %f", value); // fails (outputs random garbage value)
}

如果这是编译器 bug/issue,我使用的是 Visual Studio 2017.

In case this is a compiler bug/issue, I am using Visual Studio 2017.

不,没有编译器错误。一切都按预期工作。

Does anybody know why C++ fails on the variadic printf function?

printf("printf value: %f", value); 

不会隐式调用您的转换运算符并严格期望 float 值,而不是 Float32 实例。

它不能这样做,因为 %f 是在运行时解析的,而且 printf() 不可能知道你的 class 当时有一个转换运算符。

Is the code fixable?

您仍然必须明确地进行转换:

printf("printf value: %f", (float)value); 

由于template<typename T> std::ostream& operator<<(std::ostream, const T&)是一个模板函数,它会在编译时推断出最佳可能的转换,而这恰恰相反。