operator+ outside class definition

Started by
1 comment, last by Koldo 11 years, 11 months ago
Hello all

I am a happy new AngelScript user and I had a question.

Implementing a class with arithmetical operations like + it happens this:

[font=courier new,courier,monospace]MyClass a, b;
...
b = a + 5; [/font][font=courier new,courier,monospace]// It works with operator+ inside class
b = 5 + a; // It would require an "outside class definition" like
// MyClass operator+(const double lhs, const MyClass &rhs) {return MyClass(lhs) += rhs;}[/font]

Do you know how to implement this [font=courier new,courier,monospace]operator+ [/font]outside MyClass?.
Do you know how to do it in case of MyClass is defined in main C++ program instead of in script?

Thank you
Koldo
Advertisement
AngelScript doesn't use global operator overloads. Instead there are two variants of the operator overload methods, one for implementing operations with the other value on the right side, and another on the left side.


// AngelScript
class MyClass
{
MyClass opAdd(int rhs) const { ... } // Used for object + value
MyClass opAdd_r(int lhs) const { ... } // Used for value + object. The postfix r in the name means (reversed)
}


To register a C++ class with operator overloads, you can do the following:


// C++
class MyClass
{
public:
MyClass operator+ (int rhs) const { ... }
static MyClass operator+ (int lhs, const MyClass &rhs) { ... }
}

void Register(asIScriptEngine *engine)
{
engine->RegisterObjectType("MyClass", ... );
engine->RegisterObjectMethod("MyClass", "MyClass opAdd(int) const", asMETHOD(MyClass, operator+), asCALL_THISCALL);
engine->RegisterObjectMethod("MyClass", "MyClass opAdd_r(int) const", asFUNCTIONPR(MyClass::operator+, (int, const MyClass &), MyClass), asCALL_CDECL_OBJLAST);
}


The std script string add-on gives a more complete example of how this is done.


Regards,
Andreas

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

Thank you Andreas!

I read the documentation and string plugin but I did not realized how to do it. Now I understand smile.png .

Finally it has has worked well for me with slight changes:


// C++
class MyClass
{
public:
MyClass operator+ (int rhs) const { ... }
}
MyClass operator+ (int lhs, const MyClass &rhs) { ... }

void Register(asIScriptEngine *engine)
{
engine->RegisterObjectType("MyClass", ... );
engine->RegisterObjectMethod("MyClass", "MyClass opAdd(int) const", asMETHOD(MyClass, operator+), asCALL_THISCALL);
engine->RegisterObjectMethod("MyClass", "MyClass opAdd_r(int) const", asFUNCTIONPR(operator+, (int, const MyClass &), MyClass), asCALL_CDECL_OBJLAST);
}


Best regards
Koldo

This topic is closed to new replies.

Advertisement