重写左手操作符的可能性?
在C++中是否有覆盖和左手操作符的可能性?重写左手操作符的可能性?
例如,它很容易覆盖的右手:举个例子:
class MyClass{
public inline MyClass operator*(float &other)
{
return MyClass(this->Data * other);
}
};
所以我可以使用类似的东西:
MyClass a = MyClass(...) * 0.4f;
做什么,如果有人想这样写:
MyClass a = 0.4f* MyClass();
?
在C#中,这很容易完成,因为存在类扩展。 C++是否也知道一些解决方法?
你可以觉得像类成员函数:
ReturnType Function(TypeOfThisClass* this_, TypeOfParam param, ...)
( 您在std::thread
使用这种形式过于:(即把类PTR作为参数)
class MyClass { void Function() { ; }; }
....
MyClass myClass;
std::thread(&MyClass::Function, &myClass);
)
所以你的成员是:
class MyClass{
....
friend MyClass operator*(const MyClass& this_, float &other)
{
return MyClass(this_.Data * other);
};
/*or MyClass operator*(float &other)
{
return MyClass(this->Data * other);
};, which is the same, except you use it with reference not pointer)*/
friend MyClass operator*(float &other, const MyClass& this_)
{
return this_ * other; //you can use the overloaded op. since it is defined above (first arg is class)
};
};
,如果你想访问你的类protected
和private
数据(这应该是在OOP的情况下),你应该只使用friend
关键字。
'friend'允许访问私有数据以及受保护的数据。这里惯用的习惯是定义一个公共'MyClass&MyClass :: operator * =(MyClass const&rhs);',然后使用它定义全局'operator *'。 – 2014-11-22 16:54:42
@詹姆斯Kanze我的意思是不公开可见与“保护”,编辑。还有你说的这个成语是什么,也许我可以把它添加到答案中。我只是写下了编译器如何“看见”函数,以便更好地理解发生了什么。 – 2014-11-22 18:55:42
我在说的这个习语是,如果你支持a op b
,你也应该支持a op= b
。后者通常应该是一个成员(因为你不想在左侧进行转换),而前者很容易实现后者,所以甚至不需要成为朋友。 –
2014-11-24 10:13:41
MyClass a = 0.4f* MyClass();
MyClass a = MyClass(...) * 0.4f;
对于这些有意义的声明operator *作为类的非成员函数以及单参数构造函数。
是的,你可以声明运算符重载为自由函数。在你的情况,因为这两种操作排序具有相同的含义,你可以委托一至其它:
class MyClass
{
float data_;
public:
explicit MyClass(float data) : data_(data) { } // exposition only
MyClass operator*(float val) const { return MyClass(data_ * val); }
};
MyClass operator*(float val, MyClass const & x) { return x * val; }
现在,当你有MyClass x;
和你说x * 4
,这使用成员超载,但是当你说4 * x
,它使用自由函数,而函数又调用成员函数。
请注意,通过委托给相反的运算符,我们可以有一个简单的免费函数,它不需要知道成员函数的实现。通过constrast,如果你想重新实现从无到有的免费功能,那就需要访问类,这通常是通过使免费功能的friend
解决的私有成员,像这样:
class MyClass
{
// as above
friend MyClass operator*(float val, MyClass const & x)
{
return MyClass(x.data_ * val); // access x's private member
}
};
是的,C++有免费的功能,我不会称之为解决方法。你的例子也是错误的。你不能将'0.4f'作为'float'来传递。 – chris 2014-11-22 15:45:52