3

What's wrong in this:

i'm getting these errors for all the 5 definitions:

 error C3698: 'System::String ^' : cannot use this type as argument of 'gcnew'
 error C2512: 'System::String::String' : no appropriate default constructor available    



array<String^>^ arr = gcnew array<String^>
{
    gcnew String^ "Madam I'm Adam.",    
    gcnew String^ "Don't cry for me,Marge and Tina.",   //error C2143: syntax error : missing '}' before 'string'   AND error C2143: syntax error : missing ';' before 'string'
    gcnew String^ "Lid off a daffodil.",
    gcnew String^ "Red lost Soldier.",
    gcnew String^ "Cigar? Toss it in a can. It is so tragic."
}

2 Answers 2

5

You should not use gcnew inside the array initializer:

array<String^>^ arr = gcnew array<String^> {
    "Madam I'm Adam.",    
    "Don't cry for me,Marge and Tina.",
    "Lid off a daffodil.",
    "Red lost Soldier.",
    "Cigar? Toss it in a can. It is so tragic."
};
Sign up to request clarification or add additional context in comments.

Comments

3

The other answerer has the correct syntax, but it's not because you're in an array initializer.

There's two errors with your string initialization.

  1. When using gcnew, you don't need to include the ^. You're constructing a new object, not a new reference.
  2. You need parentheses when calling the constructor.

So the proper constructor syntax would be to call gcnew String("Madam I'm Adam.").

However, as other answerer noted, you don't need to do that. The string literal is already a String object, so you can remove the call to the constructor and just use the string literal directly. This is the same as calling new String("Madam I'm Adam.") in C#: It's already a string object, calling new String is redundant.

3 Comments

what exactly is the constructor here, in c++/cli? I know in c++ it gets called when an object is created but could u explain what it is over here and what it does.
The constructor has the same meaning and function in C++, C++/CLI, and C#. In all cases, it's invoked by new/gcnew to perform initialization after the raw memory has been allocated.
@David: Actually constructors behave quite differently in .NET vs standard C++. They have the same purpose, but details such as virtual dispatch during construction operate very differently.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.