Link to home
Start Free TrialLog in
Avatar of johnny_device
johnny_device

asked on

Problem using 'this' in static declaration


This question relates to a related solution already submitted (please see below for link)
..............................................................................................................................

When I come to implement Neun123's solution into my code, I encounter compilation problems adapting my existing program, in particular with reference to the following line in the example code:
Form2Obj = gcnew Form2((CPPForms::IForm1^)this);

1) In my version, the equivalent of Form2Obj is declared as public:static, resulting in the compiler error:
" 'this' : can only be referenced inside non-static member functions".

2) The reason it is declared as static is because otherwise I get the following error:
"only static data members can be initialized inside a ref class or value type".

Hence, I get into a circular compiler issue.

I'm guessing the discrepancy between Neun123's solution and my implementation is a question of a compiler switch '/clr:pure'.  Is that the issue, or am I barking up the wrong tree?

How can I refer to 'this' without using the 'this' keyword?   Is there another way round this?
Avatar of Orcbighter
Orcbighter
Flag of Australia image

When refering to a function within a static class you just reference that function using the class namespace.

example

static class Thinghy
{
   public bool IsOK() { return true; }

   public int DoSomething( int param1, int param2 )
   {
     int answer = 0;
     /// blah blah
    return answer;
}

Now, to access a member function

...
 if ( Thingy::IsOK() )
{
    int a = 5, b = 6;
   int ans = Thingy::DoSomething( a, b );

}
Avatar of johnny_device
johnny_device

ASKER


Hi Orcbighter, appreciate your speedy response.  However, I'm not totally clear how it relates to my particular problem.  It looks to me as though I'm not trying to access a function within the Class; what I need to do is to pass the Class itself as a parameter to a separate Form.  The syntax will not allow me to use 'this' to refer to "this Form Class", so how do I get around it?  I tried putting the class namespace itself as a parameter, but that didn't work either.

Can you tell me more literally what I would replace 'this' with in the following snippet:
Form2Obj = gcnew Form2((CPPForms::IForm1^)this);

Thanks, jd
ASKER CERTIFIED SOLUTION
Avatar of Neun123
Neun123

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you again, Neun123.  I am beginning to see that the application of logic can make things seem more logical.

You are the worthy winner of the points.


Regards,



jd