1
正在和一些基於腦測試者的朋友討論這個問題是否有效。它引導我們討論是否有可能爲任何語言的基元類型重載+
或-
。什麼(如果有)語言可以覆蓋基本類型的+運算符?
是否有任何語言在那裏你可以得到如下評價:
answer = 8 + 11;
if (answer == 96){
//Yay! It worked!
}
正在和一些基於腦測試者的朋友討論這個問題是否有效。它引導我們討論是否有可能爲任何語言的基元類型重載+
或-
。什麼(如果有)語言可以覆蓋基本類型的+運算符?
是否有任何語言在那裏你可以得到如下評價:
answer = 8 + 11;
if (answer == 96){
//Yay! It worked!
}
C#執行;不正是你想要什麼(Trick
是不基本類型),但與所需行爲:
public struct Trick {
public override bool Equals(object obj) {
return true;
}
public override int GetHashCode() {
return 0;
}
// Trick can be implicitly created from any int (e.g. from 19, 96 etc.)
public static implicit operator Trick(int value) {
return new Trick();
}
// All Trick instances are equal to each other
public static bool operator == (Trick left, Trick right) {
return true;
}
public static bool operator != (Trick left, Trick right) {
return false;
}
}
現在,我們準備測試Trick
:
Trick answer;
// ------ Now goes your fragment -----------------------
answer = 8 + 11; // Trick instance can be implicitly created from int (from 19)
// .Net can't compare answer (which is Trick) and int (96), however
// Trick instance can be implicitly created from int (from 96)
// so .Net will create Trick instance from 96 and compare two Tricks
if (answer == 96) {
// when comparing two Trick instances:
// one created from 19 and other created from 96
// they are equal to one another
Console.Write("Yay! It worked!");
}
而且你會得到
「耶!它的工作!」
C++和Ruby。
//C++
class X
{
public:
X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
{ // but often is, to modify the private members)
/* addition of rhs to *this takes place here */
return *this; // return the result by reference
}
// friends defined inside class body are inline and are hidden from non-ADL lookup
friend X operator+(X lhs, // passing lhs by value helps optimize chained a+b+c
const X& rhs) // otherwise, both parameters may be const references
{
lhs += rhs; // reuse compound assignment
return lhs; // return the result by value (uses move constructor)
}
};
紅寶石:
class String
def <<(value)
self.replace(value + self)
end
end
str = "Hello, "
str << "World."
puts str
我認爲這是說:「不,你不能,」我讀過的最好的方式。謝謝。 :) – Nick