以下是我写的Calc[] calculators = new Calc[10]; calculators[0].AddToSum(10); (编写相应的类和方法)。 但我得到“对象引用未设置为对象的实例”异常。然后通过一些研究我通过执行以下操作删除了异常。
for (int i = 0; i < 10; i++) { calculators[i] = new Calc(); }有人可以解释为什么我们需要再次分配内存,这与c / c ++不同。 这就是我在c ++中的表现:
Calculator *calc=new Calculator[10]//I know I need to check for std::bad_alloc exception calculators[0].AddToSum(10); delete[] calc;Following is the code I wrote Calc[] calculators = new Calc[10]; calculators[0].AddToSum(10); (the corresponding classes and methods are written). But I got "Object reference not set to an instance of an object" exception.Then with some research I got the exception removed by doing following.
for (int i = 0; i < 10; i++) { calculators[i] = new Calc(); }Can somebody explain why we need to allocate memory again unlike in c/c++. This is how I did it in c++:
Calculator *calc=new Calculator[10]//I know I need to check for std::bad_alloc exception calculators[0].AddToSum(10); delete[] calc;最满意答案
在C#中,有引用类型,并且有值类型。 类是引用类型。 创建引用类型的变量时,您将创建引用,而不是对象。 引用的默认状态为null。 如果您希望它引用一个对象,则必须使用new显式初始化它,或者从另一个初始化引用中分配if。
C ++没有这种区别。 每种类型都是值类型(尽管您也可以创建对任何类型的引用)。 创建值类型的变量时,您将创建一个对象。
In C#, there are reference types, and there are value types. Classes are reference types. When you create a variable of a reference type, you are creating a reference, not an object. The default state of a reference is null. If you want it to refer to an object, you have to explicitly initialize it with new, or assign if from another initialized reference.
C++ does not have this distinction. Every type is a value type (though you can also create references to any type). When you create a variable of a value type, you are creating an object.
更多推荐
发布评论