I don't understand why we need the 'new' keyword

后端 未结 6 613
情话喂你
情话喂你 2020-12-02 18:19

I am new to C#, from a C++ background. In C++ you can do this:

class MyClass{
....
};
int main()
{
   MyClass object;         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 19:06

    From the microsoft programming guide:

    At run time, when you declare a variable of a reference type, the variable contains the value null until you explicitly create an instance of the object by using the new operator, or assign it an object that has been created elsewhere by using new

    A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.

    A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.

    I think in your C# example your effectively trying to assign values to a null pointer. In c++ translation this would look like:

    Car* x = null;
    x->i = 2;
    x->j = 3;
    

    This would obviously compile but crash.

提交回复
热议问题