int的默认构造函数 [英] default constructor for int

查看:669
本文介绍了int的默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么使用空的一组括号来调用没有参数的构造函数的错误?


这个问题它是说


ints默认构造为0,因为如果你用int()初始化它们。其他原始类型的初始化类似(例如double(),long(),bool()等)。


我向我的同事解释这一点,我编写了以下代码,编译(gcc-4.3.4)并运行,并观察到意外行为。

  #include< iostream> 

int main(){
int i();
std :: cout<< i<< std :: endl; // output is 1
}

为什么输出 1 $ >最讨厌的解析在这里发挥作用。你实际上声明了一个函数 i ,而不是一个 int 变量。它不应该编译(除非你实际上有一个函数 i 在某处定义... 你是吗?)。



要初始化int,你需要:

  int i = int 


Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

In an answer to this question it's said that

ints are default-constructed as 0, as if you initialized them with int(). Other primitive types are initialized similarly (e.g., double(), long(), bool(), etc.).

Just while I was explaining this to a colleague of mine I made up the following code, compiled (gcc-4.3.4) and ran, and observed unexpected behavior.

#include <iostream>

int main() {
  int i(); 
  std::cout << i << std::endl; // output is 1
}

Why is the output 1 but 0 ?

解决方案

Most vexing parse comes into play here. You're actually declaring a function i, not an int variable. It shouldn't even compile (unless you actually have a function i defined somewhere... do you?).

To value-initialize the int, you need:

int i = int(); 

这篇关于int的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆