为什么结果输出到1(Why result is outputted to 1)

编程入门 行业动态 更新时间:2024-10-23 15:21:59
为什么结果输出到1(Why result is outputted to 1)

我有一个简单的程序,如下所示

#include<iostream> using namespace std; class A { public: A() { int a(); cout<<"\n value of A is:- "<<a<<"\n\n"; } }; int main() { A obj; return 0; }

上面的程序正在输出一个,虽然我没有给变量a传递任何值。 如果我用任何变量保存(),它是一些构造函数正在执行的任务还是其他类型的默认构造函数。

float数据类型也一样。

它看起来很简单,但我想了解这背后的概念。 有人可以帮助我吗?

I am having a simple program as shown below

#include<iostream> using namespace std; class A { public: A() { int a(); cout<<"\n value of A is:- "<<a<<"\n\n"; } }; int main() { A obj; return 0; }

The above program is outputting one, although I am not passing any value to variable a. Is it some task constructor is performing or some other type of default constructors are called, if I keep () with any variable.

Same is happening for float datatype also.

It look simple but I want to understand the concept behind this. Can someone please help me with that?

最满意答案

int a()声明一个名为a的函数,不带任何参数并返回int 。 当你尝试输出一个函数时,它会被转换成一个函数指针,该函数指针又被转换为bool 。 函数的地址总是非空的,所以它被转换为true ,打印为1。

但请注意,您违反了One Definition Rule:如果函数缺少定义,则不允许使用函数的地址。 但是,编译器不需要诊断ODR的违规。 在这种特殊情况下,编译器决定它并不关心实际地址,因为它知道不管它是什么,它都是非空的。

如果你想声明一个int和值 - 初始化它,那么正确的语法是

int a{};

http://coliru.stacked-crooked.com/a/6d10bdd34c238ab6

int a() declares a function named a, taking no arguments and returning int. When you try to output a function, it gets converted to a function pointer, which in turn is converted to bool. The address of a function will always be non-null, so it gets converted to true, which is printed as 1.

Note however that you are violating the One Definition Rule: you're not allowed to take the address of a function if the function lacks a definition. However, the compiler is not required to diagnose violations of the ODR. In this particular case, the compiler decides it doesn't care about the actual address, since it knows that it will be non-null no matter what.

If you want to declare an int and value-initialize it, the correct syntax is

int a{};

http://coliru.stacked-crooked.com/a/6d10bdd34c238ab6

更多推荐

本文发布于:2023-07-30 22:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340336.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:result   outputted

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!