您的位置:首页 > 编程语言 > C语言/C++

C++/CLI学习入门(十):类的运算符重…

2014-11-13 19:42 148 查看
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

C++/CLI中可以对运算符进行重载,但与本地C++有所区别。同时对于运算符重载,数值类和引用类也存在不同要求。下面以例子开始,了解C++/CLI中重载运算符的方法。

一、数值类中重载运算符
下面的例子重载了加法运算符。

value class Length

{

private:

int feet;

int inches;

public:

static initonly int inchesPerFoot = 12;

Length(int ft, int ins) : feet(ft), inches(ins) {}

virtual String^ ToString() override

{ return feet+L" feet "+inches+L" inches"; }

Length operator+(Length len)

{

int inchTotal = inches + len.inches + inchesPerFoot*(feet +
len.feet);

return Length(inchTotal/inchesPerFoot,
inchTotal%inchesPerFoot);

}

};
类的使用很简单,方法如下

Length len1 = Length(6, 9);

Length len2 = Length(7, 8);

Console::WriteLine(L"{0} plus {1} is {2}", len1, len2, len1+len2);

上面重载的加法运算符也可通过静态成员的方式实现。

static Length operator+(Length len)

{

int inchTotal = inches + len.inches + inchesPerFoot*(feet +
len.feet);

return Length(inchTotal/inchesPerFoot,
inchTotal%inchesPerFoot);

}

下面定义Length与数值的乘法重载运算符,它包括了数值*长度长度*数值两种情况。这也是二元操作的一个例子

value class Length

{

//...

static Length operator*(double x, Length len);

static Length operator*(Length len, double x);

};
?? 函数的定义如下

Length Length::operator*(double x, Length len)

{

int ins = safe_cast<int>(x*len.inches
+ x*len.feet*inchesPerFoot);

return Length( ins/12, ins%12 );

}

length Length::operator*(Length len, double x)

{

return operator*(x, len);

}

下面定义递增运算符,这是一个一元运算符,可用同一个函数来定义前缀递增和后缀递增运算,编译器能够自动的根据调用情况来判断是先递增还是后递增。

static Length operator++(Length len)

{

++len.inches;

len.feet += len.inches/len.inchesPerFoot;

len.inches %= len.inchesPerFoot;

return len;

}二、引用类中重载运算符

在引用类中重载运算符的方法与数值类基本相同,主要区别是形参和返回值一般都是句柄。这里就不再赘述了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: