简体   繁体   English

C ++类-指针问题

[英]C++ Classes - Pointers question

I had a quiz at school and there was this question that I wasn't sure if I answered correctly. 我在学校里进行了一个测验,但有一个问题我不确定我是否回答正确。 I could not find the answer in the book so I just wanted to ask you. 我在书中找不到答案,所以我只想问你。

Point* array[10];

How many instances of class Point are created when the above code is called? 调用上述代码时,会创建多少个Point类实例?

I answered none because it only creates space for 10 instances, but doesn't create any. 我没有回答,因为它只会为10个实例创建空间,而不会创建任何实例。 Then my friend said it was just one because when the compiler sees Point* it just creates one instance as a base. 然后我的朋友说这只是一个,因为当编译器看到Point *时,它只是创建一个实例作为基础。

It creates no Point s. 它不创建Point

What it does is creates an array of ten pointers that can point to Point objects (it doesn't create space for ten instances ). 它的作用是创建一个包含十个指针的数组,这些指针可以指向Point对象(它不会为十个实例创建空间)。 The pointers in the array are uninitialized, though, and no Point objects are actually created. 但是,数组中的指针未初始化,并且实际上没有创建Point对象。

You are almost correct. 你几乎是正确的。

The code creates no instances of Point . 该代码不创建Point实例。 It does create 10 instances of Point * , though. 但是,它确实创建了Point * 10个实例。 It does not create the space for the Point instances; 并不创造的空间 Point情况; that is done using a call to new , for example. 例如,通过调用new完成。

Point* array[10] creates an array with ten slots for pointers, numbered 0..9. Point* array[10]创建一个带有十个指针插槽的数组,编号为0..9。

You are both wrong - no initialisation takes place in C++ with such a statement, unless 你们都错了-除非这样,否则C ++中不会进行初始化

  1. you are running a special memory allocator which zeros memory, such as SmartHeap (or C++/CLI) or 您正在运行将内存清零的特殊内存分配器,例如SmartHeap(或C ++ / CLI)或
  2. if the array is outside of a function (eg: just within a .cpp file as global), in which case all the pointers are zeroed. 如果数组在函数外部(例如:仅在.cpp文件中作为全局变量),则所有指针均归零。

Absolutely no instances are created. 绝对不会创建任何实例。

Respectfully disagreeing with strager's point, there is no such thing as an instance of Point* and it would be dangerous to think of such a thing existing. 完全不同意strager的观点,没有Point *的实例 ,想到存在这样的事物将很危险。 There is only space for a pointer and compile-time checking to ensure you can only assign a pointer of that type, or pointer to a subclass, into that pointer. 指针和编译时检查只有空间,以确保您只能将该类型的指针或指向子类的指针分配给该指针。

no initialisation takes place in C++ with such a statement 这样的语句在C ++中不会发生初始化

The Point* objects in array are zero-initialized if array is global. Point*的对象array是如果零初始化array是全球性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM