重载运算符
更新:2007 年 11 月
从 C++ 托管扩展到 Visual C++ 2008,运算符重载发生了明显的更改。
例如,在引用类型的声明中,您可以显式写出运算符的基础内部名称(在这种情况下,为 op_Addition),而不使用本机 operator+ 语法。此外,必须通过该名称显式调用运算符的调用,这样会排除运算符重载的两个主要好处:(a) 语法直观和 (b) 具有将新的类型与现有类型混合的功能。例如:
public __gc __sealed class Vector {
public:
Vector( double x, double y, double z );
static bool op_Equality( const Vector*, const Vector* );
static Vector* op_Division( const Vector*, double );
static Vector* op_Addition( const Vector*, const Vector* );
static Vector* op_Subtraction( const Vector*, const Vector* );
};
int main()
{
Vector *pa = new Vector( 0.231, 2.4745, 0.023 );
Vector *pb = new Vector( 1.475, 4.8916, -1.23 );
Vector *pc1 = Vector::op_Addition( pa, pb );
Vector *pc2 = Vector::op_Subtraction( pa, pc1 );
Vector *pc3 = Vector::op_Division( pc1, pc2->x );
if ( Vector::op_Equality( pc1, pc2 ))
;
}
在新的语法中,在声明和静态运算符的使用中将还原本机 C++ 程序员的常见期望值。以下是转为使用新语法的 Vector 类:
public ref class Vector sealed {
public:
Vector( double x, double y, double z );
static bool operator ==( const Vector^, const Vector^ );
static Vector^ operator /( const Vector^, double );
static Vector^ operator +( const Vector^, const Vector^ );
static Vector^ operator -( const Vector^, const Vector^ );
};
int main()
{
Vector^ pa = gcnew Vector( 0.231, 2.4745, 0.023 );
Vector^ pb = gcnew Vector( 1.475,4.8916,-1.23 );
Vector^ pc1 = pa + pb;
Vector^ pc2 = pa - pc1;
Vector^ pc3 = pc1 / pc2->x;
if ( pc1 == pc2 )
;
}