使用new关键字创建对象数组(C#,C++,Java)

今天遇到一个题目

分析下面的代码,判断代码是否有误。

 1 using System;
 2 
 3 namespace Test1
 4 {
 5     class Point
 6     {
 7         public int x;
 8         public int y;
 9     }
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             Point[] pointArr = new Point[3];
15             pointArr[0].x = 5;
16             pointArr[0].y = 6;
17             pointArr[1].x = 8;
18             pointArr[1].y = 16;
19             pointArr[2].x = 15;
20             pointArr[2].y = 26;
21         }
22     }
23 }

创建了3个对象数组,然后给对象的属性赋值,很明显是正确的吧。
然而!编译能通过,运行却报错!

可以很明显的看到,空引用异常
逐行debug可以发现,当运行到pointArr[0].x = 5;这一句时,异常就产生了
显然,说明pointArr[0]不存在属性x,也就是说,pointArr[0]并不是一个Point对象
它为null
问题出在哪?
这是因为,当我们使用new关键字来创建对象数组时,并不会创建这个类的对象
那么你就要问了,使用了new却不创建对象,new的意义何在?
其实,在使用new关键字创建对象数组时,系统只是在内存中给他开辟了空间而已
看到这里,你可能还是不会相信,那么我们思考一下,创建对象必须调用对象的构造函数吧,那我们重写构造函数,看看会输出什么?
代码如下:

 1 using System;
 2 
 3 namespace Test1
 4 {
 5     class Point
 6     {
 7         public Point() { Console.WriteLine("这是一个构造函数"); }
 8         public int x;
 9         public int y;
10     }
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Point[] pointArr = new Point[3];
16             pointArr[0].x = 5;
17             pointArr[0].y = 6;
18             pointArr[1].x = 8;
19             pointArr[1].y = 16;
20             pointArr[2].x = 15;
21             pointArr[2].y = 26;
22         }
23     }
24 
25 }

我们接着运行
仍然报错,而且并未输出构造函数内的内容

到这里,已经很明显了,使用new创建对象数组时,不会真的创建对象!
当然,以上只是C#中的结论
我们接下来换C++

 1 #include "pch.h"
 2 #include <iostream>
 3 using namespace std;
 4 class Point
 5 
 6 {
 7 public:
 8     int x;
 9     int y;
10     Point() {
11         cout << "这是一个构造函数" << endl;
12     }
13 
14 };
15 int main()
16 {
17         Point * pointArr = new Point[3];
18         pointArr[0].x = 5;
19         pointArr[0].y = 6;
20         pointArr[1].x = 8;
21         pointArr[1].y = 16;
22         pointArr[2].x = 15;
23         pointArr[2].y = 26;
24 }

运行:

咦??????????
为什么成功调用了构造函数????
有点迷.......
果然C++和C#还是很不一样的。。。
事情变得有趣起来了呢
我们换java!

 1 package pack1;
 2 
 3 class Point
 4 {
 5     public int x;
 6     public int y;
 7     public Point() {
 8         System.out.println("这是一个构造函数");
 9     }
10 
11 };
12 public class TestJava {
13     public static void main(String[] args) {
14         Point[] pointArr = new Point[3];
15         pointArr[0].x = 5;
16         pointArr[0].y = 6;
17         pointArr[1].x = 8;
18         pointArr[1].y = 16;
19         pointArr[2].x = 15;
20         pointArr[2].y = 26;
21     }
22 }

运行!

空指针报错
说明java里的new关键字创建对象数组时,也是不会创建对象的

总结:
在面向对象语言中,new关键字基本都是只开辟空间,不创建对象的。而C++作为非纯面向对象语言,在设计方面与面向对象语言还是有很大的不同。
----------------------------------------------------------------------------
大家好,我是ABKing

金麟岂是池中物,一遇风云便化龙!
欢迎与我交流技术问题

猜你喜欢

转载自www.cnblogs.com/ABKing/p/11965225.html