[英]Define operator ** in C++
如何定義運算符**
,使其可以執行2個數的取冪。 例如2 ** 3
。 應該給出答案為8。
或間接有任何方法我可以用運算符重載代替#define
宏來做到這一點?
你不能。 您只能重載現有的運算符,而不能重載內置類型。
你不能。 您只能在C ++中重載現有的運算符; 你不能添加新的,或改變現有運營商的arity或關聯性。 甚至預處理器在這里也是無能為力的 - 它的標識符不能是符號。
如果你願意作出妥協WRT **
,感覺就像弄亂你的代碼:
#include <cmath>
#include <iostream>
struct foo {
foo(int i) : i_(i) {}
int operator*(int exp)
{
return std::pow(i_,exp);
}
private:
int i_;
};
struct bar {
} power_of;
foo operator*(int i, bar)
{
return foo{i};
}
int main()
{
std::cout << 2 *power_of* 3; // prints 8
}
否則,只需使用std::pow
。
與其他注釋一樣,這對於內置類型是不可能的, 但是你可以讓它適用於這樣的自定義類型(最小代碼示例):
#include <cmath>
#include <iostream>
struct dummy;
struct Int
{
int i;
Int() : i(0) {}
Int(const int& i) : i(i) {}
dummy operator*();
};
struct dummy
{
Int* p;
dummy(Int* const p) : p(p) {}
int& operator*()
{
return p->i;
}
};
dummy Int::operator*()
{
return dummy(this);
}
int operator*(const Int& lhs, const dummy& rhs)
{
return std::pow(lhs.i, rhs.p->i);
}
int main()
{
Int a(2);
Int b(2);
std::cout<< a ** b << std::endl;
}
正如其他人所指出的那樣: 這是不可能的。 你可以重載另一個運算符,比如^
,用於取冪,而不是在一個簡單的類型包裝器類/對象上。
但是,如果你喜歡冒險,另一種方法是創建一個微型DSL,支持這種運營商的即時計算。 (一個着名的例子是C ++中的LISP)
然而,考慮到所涉及的努力,它可能是也可能不是你的一杯茶。 但是,值得知道存在這種可能性。
更新:
運算符重載通過重載已有的運算符來工作。 為什么? 因為如果您可以定義自己的,那么您還必須定義這些運算符的優先級,這些運算符可以通過抽象掉它們的原始目的輕易讓位於濫用運算符 - 這會增加閱讀代碼時的難度。 (至少這是已經提出的論點)。
具有接近**
的語義含義的最接近的運算符是插入符號運算符。 這種運算符的簡單和說明性實現是:
#include <iostream>
#include <cmath>
class Int {
public:
Int() {}
Int(int i) : value(i) {}
friend double operator^(const int& i, const Int& integer);
friend double operator^(const Int& integer, const int& i);
friend double operator^(const Int& lhs, const Int& rhs);
private:
int value;
};
double operator^ (const int& lhs, const Int& rhs) {
return std::pow(lhs, rhs.value);
}
double operator^ (const Int& lhs, const int& rhs) {
return std::pow(lhs.value, rhs);
}
double operator^ (const Int& lhs, const Int& rhs) {
return std::pow(lhs.value, rhs.value);
}
int main() {
Int i1 = 10;
Int i2 = 3;
double result = i1 ^ i2;
std::cout << result;
return 0;
}
您不能為內置類型重載運算符。 為了自定義類型,我會使用operator ^
。
不幸的是,可以在C ++中重載的運算符集是固定的,不包括**運算符。 您可能會考慮使用operator^()
,但事實證明^具有錯誤的優先級來充當指數運算符。
簡而言之,遺憾的是,你無能為力。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.