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

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;
}二、引用类中重载运算符

在引用类中重载运算符的方法与数值类基本相同,主要区别是形参和返回值一般都是句柄。这里就不再赘述了。

<script type="text/javascript" id="wumiiRelatedItems"> </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值