0

我想知道“int”是否被定义为一个类,这意味着就像某个头文件中的某个地方它们是一个名为 int 的类

class int
{

}

当我们声明一个变量时,会创建一个 int 类的实例吗?如果'int'是一个类,它存储在哪个文件中?

4

4 回答 4

4

No; int is not a type of "class-type". It is a so-called "scalar" type.

To determine more generally whether a given object type T is of scalar, array, union or class type, you can #include <type_traits> and use std::is_scalar<T>::value, and similarly for the traits is_array, is_union and is_class.

(Note further that not all types are object types; there are also reference types and function types. You can use std::is_object and is_function and is_reference to make that distincition first.)

于 2012-10-12T19:44:08.897 回答
1

int is not a class, its a native type.

When you declare an int:

int x;

You do create an instance of int.

C++ is different than many other languages in this respect where, like in Java or Ruby for instance, "everything is an object." This generally means that everything is derived from one root class, or at least appears to be.

Consider for example Ruby, where everything is ultimately derived from Object. Object, in turn, is implemented as a fully-fledged class. It has methods on it like to_s and code that implements those methods.

C++ isn't like that. C++ has very basic types, like int, that aren't derived from anything. There's no code behind these types, and they have no methods on them. You can't do something like this:

int x = 42;
string s = x.to_s();

because there's no to_s() method on an int, or any methods.

You also asked,

If 'int' is a class , in which file it is stored??

int isn't "stored" in any file. The meaning and definition of an int is built in to the compiler itself. There's no file that you can open on your machine to see how an int is defined. When you do something like:

int x = 42;
x += 77;

...the compiler doesn't have to look in any header file to know how to add 77 to 42. It already knows, because and int is something that the compiler already knows about. Almost like a-priori knowledge, it's "just there".

How does the compiler already know? Because the people who wrote the compiler (probably using C or C++, by the way) coded that knowledge in. How did the compiler writes know what to write? They followed a document, called the C++ Standard, which explains exactly how a conformant compiler should behave.

于 2012-10-12T19:41:21.347 回答
0

不,int是基本类型,定义如下:

3.9.1 基本类型[basic.fundamental]

2)有五种有符号整数类型:“<code>signed char”、“<code>short int”、“<code>int”、“<code>long int”和“long long int”。在此列表中,每种类型提供的存储空间至少与列表中它前面的类型一样多。普通整数具有执行环境架构所建议的自然大小);提供其他有符号整数类型以满足特殊需要。

于 2012-10-12T19:45:42.073 回答
0

No, int is a built-in type. It is not a class. The compiler has built-in knowledge of how to deal with int.

于 2012-10-12T19:41:34.050 回答