gpt4 book ai didi

c++ - #在c++中定义一个特殊的运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:06:56 25 4
gpt4 key购买 nike

假设我想在两个对象之间在 C++ 中组成一个特殊的运算符 !+。例如,我想使用 !+,因为我认为它比任何其他运算符都更有意义。

我能做的一件基本事情是找到一个免费的、未使用的运算符并使用#define 进行替换:

#define !+ %
class myclass
{
public:
int operator %(myclass &c)
{
return 3;
}
}

所以如果我以后写类似的东西

a!+b 

对于 myclass 的 a 和 b 实例,它会起作用。

现在,有没有什么方法可以用运算符来定义它,而不是用一些函数来定义它?像这样的东西:

#define a!+b -> a.operatorexclamativeplus(b)

这将使翻译变得不那么脏,并且可能允许无限数量的这些新的“假操作符”!

最佳答案

"Now, is there any way to define it instead that with an operator, with some function?"

不,!+ 不构成预处理器宏的有效(正常)标识符。这些字符是为语言内部运算符保留的。

可用于宏定义的字符集是[_A-Za-z][_A-Za-z0-9]*regex syntax 1

来自 c++ standards definitions 草稿部分

16 Preprocessing directives

...
control-line:
...
# define identifier replacement-list new-line
# define identifier lparen identifier-listopt) replacement-list new-line
# define identifier lparen ... ) replacement-list new-line
# define identifier lparen identifier-list, ... ) replacement-list new-line


更新:
我对此进行了一些试验,因为这实际上是一个有趣的问题,如果不是 #define 的宏,我们可以为 C++ 中的类使用重载内部运算符函数。

我发现实际上有可能(但可能是奇怪的和意外的行为)选项,通过链接它们并保持状态来重载内部运算符的组合。对于您的新引入的运算符,您可以获得的最接近的东西可能是:

class Foo {
enum OpState { None , PlusState , NotState };
public:
Foo& operator+() {
cout << "operator+()" << endl;
opState = PlusState;
return *this;
}
Foo& operator!() {
cout << "operator!()" << endl;
switch(opState) {
case PlusState:
operatorexclamativeplus();
break;
default:
opState = NotState;
break;
}
return *this;
}
private:
Foo& operatorexclamativeplus() {
cout << "operatorexclamativeplus()" << endl;
opState = None;
return *this;
}
Foo& operatorexclamativeplus(const Foo& rhs) {
cout << "operatorexclamativeplus(const Foo& rhs)" << endl;
opState = None;
return *this;
}
OpState opState;
};

int main() {
Foo x;
Foo z = !+x;
return 0;
}

输出

operator+()
operator!()
operatorexclamativeplus()

参见 live sample .


虽然,因为 operator precedence rules , 这仅适用于一元运算符(! 的优先级高于二进制 +),您想要的形式似乎实际上无法实现:

class Foo {
// ...
public:
// Provide an additional binary 'operator+()'
friend Foo& operator+(Foo& lhs, const Foo& rhs) {
cout << "operator+(Foo& lhs, const Foo& rhs)" << endl;
if(lhs.opState == NotState) {
return lhs.operatorexclamativeplus(rhs);
}
return lhs;
}
// ...
};

int main() {
Foo x;
Foo y;
Foo z = y !+ x;
return 0;
}

See this miserably fail .


结论:

  1. 一些内在运算符的重载组合可能是语法上可能,关于它们的优先级定义,和维持左值的状态。
  2. 尝试重载 intrinsic 可能不是一个好主意运算符行为,引入全新的语义。

______________________________________________________________________________________

1)关于标识符的前导下划线 (_,__) 请阅读 this answer 中提到的标准部分, 这些在句法上是有效的。

关于c++ - #在c++中定义一个特殊的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25983663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com