Ghost
Ghost

Reputation: 1835

How to define an array of strings in C++/CLI?

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."
}

Upvotes: 3

Views: 5197

Answers (2)

David Yaw
David Yaw

Reputation: 27864

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.

Upvotes: 3

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262999

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."
};

Upvotes: 5

Related Questions