我可以使用 std::string 变量作为运算符的参数吗?

亚历克斯

例如,如果我有:

#include <iostream>

using namespace std;

int main()
{
    int b = 1;
    int c = 2;
    string a = "(b + c)";
    
    cout << (4 * a) << "\n";

    return 0;
}

是否可以像代码所说的那样将字符串按字面意思a解释cout << (4 * (b + c)) << "\n";

埃罗里卡

不,C++ 不是(设计为)解释型语言。

尽管理论上可以覆盖不同类型的运算符,但非常不建议覆盖不涉及您自己类型的运算符。从标准库定义运算符重载std::string可能会在将来中断。这只是个坏主意。

但是,假设您使用了自定义类型。您可以编写一个程序,将文本字符串解释为算术表达式。这种程序的核心是解析器。这当然是可能的,但是标准库没有为您提供这样的解析器。

此外,这样的解析器将无法在文本中的“b”和变量之间建立联系b在程序运行时,它不知道用于编译程序的变量名。您必须使用某种形式的数据结构来指定此类信息。

PS您忘记包含定义的标题std::string

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我可以使用变量作为比较运算符吗?

std :: string + =运算符不能将0作为参数传递

可以在constexpr中使用std :: string吗?

我可以使用std :: unique_lock来连接JNI的AttachCurrentThread和DetachCurrentThread吗?

我可以使用std :: bind将状态“附加”到函数吗?

可以使用任意字符作为运算符吗?

std :: string运算符+与stringstream的性能

我可以让std :: string使用更少的内存吗?

我可以使用按位运算符代替逻辑运算符吗?

每当需要字符串文字时,可以使用std :: string :: c_str()吗?

std :: shared_ptr-我可以使用等号(=)进行初始化吗?

我可以在Swift中使用运算符作为默认函数参数吗?

是否可以使std容器使用默认的新运算符?

std :: string未使用=运算符更新

我可以使用std :: partial_sort对std :: map进行排序吗?

我可以使用std :: generate获得std :: array <T,2>的向量吗?

我可以在>>运算符中使用std:fixed或std :: setprecision()吗?

是否可以将带有一对std:string和std :: vector <int>的std :: map重载<<运算符?

我可以使用带有C ++ 17的std :: any指向成员变量的指针吗?

我可以使用istream_iterator <char>将一些istream内容复制到std :: string吗?

使用MINGW gcc编译时,不会为std :: string调用重载的new运算符

RxJs:可以将运算符作为参数传播到管道运算符中吗

我可以使用std :: string * argv作为主要函数参数吗?

std :: set :: insert()可以调用赋值运算符吗?

使用+ =运算符可以安全地使用[]创建新的std :: map条目吗?

使用std :: string定义运算符=

为什么在std :: string上使用Sizeof运算符会产生意外结果?

使用扩展运算符作为参数

我可以使用逻辑 OR(||) 运算符而不是逻辑 AND(&&) 运算符吗