Windows 8上的Dev c++ 5.11出现错误答案

Dev c++ 5.11 on Windows 8 Produces wrong answer

本文关键字:11出 错误 答案 c++ 上的 Dev Windows      更新时间:2023-10-16
#include<iostream>
#include<conio.h>
class Number
{
    private:
    int x, y;
    public:
    Number()
    {
    x = y = 100;
    }
void avg()
{
    std::cout<<"x = "<<std::cout<<x;
    std::cout<<std::endl;
    std::cout<<"Y =  "<<std::cout<<y;
    std::cout<<std::endl;
    std::cout<<"Average =  "<<std::cout<<(x+y)/2;
}
};
     main() 
    {
    Number n;
    n.avg();
    }

程序运行,但显示错误的答案,可能是显示内存位置的地址,而不是显示分配的值100。请纠正我为什么它是这样的行为?

std::cout << "x = " << std::cout << x;

是错误的。你需要

std::cout << "x = " << x;

否则,当调用operator<<时,...<< std::cout中的std::cout流对象隐式转换为(void*),因此显示指针(地址)。

void*的转换由于历史原因(安全的bool习惯用法)而存在,但在c++ 11中由于引入了显式转换操作符而被删除,因此您的代码不应该在c++ 11中编译。