今天遇到一个题目java
分析下面的代码,判断代码是否有误。ios
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 }
咱们接着运行
仍然报错,并且并未输出构造函数内的内容spa
到这里,已经很明显了,使用new建立对象数组时,不会真的建立对象!
固然,以上只是C#中的结论
咱们接下来换C++debug
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!3d
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关键字建立对象数组时,也是不会建立对象的code
总结:
在面向对象语言中,new关键字基本都是只开辟空间,不建立对象的。而C++做为非纯面向对象语言,在设计方面与面向对象语言仍是有很大的不一样。
----------------------------------------------------------------------------
你们好,我是ABKing
金麟岂是池中物,一遇风云便化龙!欢迎与我交流技术问题