不能在引用类型上使用 'new';使用 'gcnew' 代替

cannot use 'new' on the reference type; use 'gcnew' instead

我正在尝试使用此代码:

private: System::Void button1_Click_1(System::Object^  sender, System::EventArgs^  e) {
    // Displays an OpenFileDialog so the user can select a Image.
    OpenFileDialog^ OpenFileDialog1 = new OpenFileDialog();
    openFileDialog1->Filter = "Images|*.jpg";
    openFileDialog1->Title = "Choose Image";

    // Show the Dialog.
    // If the user clicked OK in the dialog and
    // a file was selected, change picture.
    if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK){
        pictureBox1->Image = Image::FromFile(openFileDialog1->FileName);
    }
}

我从 msdn 文档中编写了这段代码:https://msdn.microsoft.com/en-us/library/61097ykx(v=vs.110).aspx

但我收到错误:

Error 1 error C2750: 'System::Windows::Forms::OpenFileDialog' : cannot use 'new' on the reference type; use 'gcnew' instead

Error 2 error C2440: 'initializing' : cannot convert from 'System::Windows::Forms::OpenFileDialog *' to 'System::Windows::Forms::OpenFileDialog ^'

如何解决?

这里的错误信息很有帮助。使用 gcnew 代替:

OpenFileDialog^ OpenFileDialog1 = gcnew OpenFileDialog();
                                  ^^^^^^

new 用于指针,gcnew 用于垃圾收集对象(因此 gc)。