Creating Classes

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Using Visual Studio 2005, I'm trying to create a simple unmanaged C++ class
that will be called from a VB application. I've got the class working using
basic functions, but I'd like to overload the "=" operator so the VB app can
assign values directly to the class. When I use "operator=", VB tells me
that I can't assign an integer to my class.

Here's what I've got:
#pragma once

using namespace System;

namespace Server {

public ref class Test2
{
private:
int iValue;

public:
void SetVal(int Value) {
iValue = Value;
}

int GetVal(void) {
return iValue;
}

int operator= (int Value) {
iValue = Value;
return iValue;
}
};
}


This is the Visual Basic portion:
Dim obj1 As New Server.Test2

obj1.SetVal(8) 'This part works!
Debug.Print(obj1.GetVal.ToString)

obj1 = 10 'This statement says: Value of type
'Integer' cannot be converted to 'Server.Test2'.
Debug.Print(obj1.ToString) 'This fails, too.
 
The assignment operator assigns a value of a type to a variable of that
type. In your case, you've overloaded the assignment operator for an
integer, by declaring the type of the operator and the operand as int. So,
what your VB code is saying is that an integer named "obj1" (which is of
type "Server") should be assigned an integer value. What your operator
overload does *not* do is to define an assignment operator for a member of
the class. In other and simpler terms, you do not understand how and why
operator overloading works.

The following is a link to the MSDN2 online reference for operator
overloading in managed C++:
http://msdn2.microsoft.com/en-us/library/5tk49fh2.aspx

This link is specifically about assignment operator overloading:

http://msdn2.microsoft.com/en-us/library/7ac5szsk.aspx

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Development Numbskull

Abnormality is anything but average.
 
Back
Top