Search code examples
managed-c++

Managed class does not compile


I have the following code in Visual C++:

#using <mscorlib.dll>

using namespace System;

__gc class classEx
{
public:
    classEx()
    {
        data = "abcd";
    }

    classEx(String *s)
    {
        data=s;
    }

    String* getNombre()
    {
        return data;
    }

    void setNombre(String *s)
    {
        data=s;
    }

    private:
        String* data;
};

int main(void)
{
    classEx* obj = new classEx();
    return 0;
}

I have changed the Configuration Manager to Release and Build is checked. The problem is when I try to compile it appears a bunch of errors, such as:

  • error C4980: '__gc' : use of this keyword requires /clr:oldSyntax command line option
  • cannot use this indirection on type 'System::String'

The last error points that I cannot use in the second constructor the String *s. Why is that?

Is there something that I am missing?


Solution

  • If you will set a corresponding compiler option to clr:oldsyntax in the project properties as the first message says, then the following code compiles without errors in Visual Studio 2010:

    #include "stdafx.h"
    
    using namespace System;
    
    __gc class A
    {
    public:
        A( String *s ) : data( s ) {}
        String * get_data() { return data; }
    private:
        String *data;
    };
    
    int main()
    {
        A *pa = new A( "Hello World" );
    
        Console::WriteLine( pa->get_data() );
    
        return 0;
    }
    

    It seems that the second message is the result of that you did not set the option pointed out in the first message.

    You should select menu ProjectPropertiesGeneral → *Supporting of CLR (or something else because I have the Russian release of Visual Studio 2010 I can not name the option exactly in English) → clr:oldsyntax