可以将运算符*重载为int和char*的倍数
Possible to overload operator* to multiple an int and a char*?
我想获得功能,这样我就可以做到这一点:
std::cout << "here's a message" << 5*"n";
我尝试了以下方法:
std::string operator* (int lhs, const char* rhs) {
std::string r = "";
for(int i = 0; i < lhs; i++) {
r += rhs;
}
return r;
}
我收到了一条错误消息:
error: ‘std::string operator*(int, const char*)’ must have an argument of class or enumerated type
根据这个SO帖子中的答案什么是';必须具有类或枚举类型的参数';实际上,这段时间我好像做不到。真的是这样吗?如果没有,我该如何解决此问题或安排变通方法?
我知道我可以做的是将rhs
作为std::string
,但这项练习的全部要点已经有一半了,因为5*std::string("n")
相当笨拙。
来自[over.oper]:
运算符函数应为非静态成员函数或具有至少一个参数,其类型为类、对类的引用、枚举或对枚举。
因此,不能重载参数都是内置的运算符。此外,为了找到operator*(int, std::string)
,它必须在namespace std
中,并且向该名称空间添加定义是不正确的。
相反,您可以简单地提供一个小包装:
struct Mult { int value; };
并为其提供过载:
std::string operator*(const Mult&, const char* );
std::string operator*(const char*, const Mult& );
从这里的C++常见问题解答,
C++语言要求您的运算符重载至少占用一个"类类型"或枚举类型的操作数。C++语言将不允许定义所有操作数/参数都为基元类型的。
您应该能够使用用户定义的文字来实现它。例如:
#include <iostream>
#include <string>
std::string operator"" _s(const char* s) { return std::string(s); }
std::string operator"" _s(const char* s, std::size_t len) { return std::string(s, len); }
std::string operator* (unsigned int k, std::string s) {
std::string t;
for (unsigned int i = 0; i < k; ++i)
t += s;
return t;
}
std::string operator* (std::string s, unsigned int k) { return k * s; }
int main() {
std::cout << "Jump!"_s * 5 << "n";
}
您既不能也必须重载该操作;
字符串ctor(2)为您完成的工作
#include <iostream>
#include <string>
int main() {
std::cout << "here's a message:n"
<< std::string(5, 'n')
<< "EOF" << std::endl;
}
输出:
here's a message:
EOF
(住在Coliru)
相关文章:
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 如何在不强制转换每个参数的情况下删除初始值设定项列表中从 int 到 char 的缩小转换?
- C ++如何在使用"tolower"时将char转换为int
- C++ (U256)*(H256 const*)(char*[] + int) 将重写转换为 Java
- char*(int)在C 中是什么意思
- 是否可以<char> <int> 在 C++ 中将 std::list 转换为 std::list
- Qt5 对'QApplication::QApplication(int&, char**, int)'的未定义引用
- 没有运算符"="匹配这些操作数操作数操作数类型为 std::basic_ostream<char、std::char_traits<char>> = int
- 编程语言中的 char-int 等价性
- C++。为什么 std::cout << char + int 打印 int 值?
- 关于运行良好的堆栈RPN程序上的char/int
- 在 C# 中从 char int 直接转换为 char
- 从文本文件中提取特定值(char & int)并插入到多个变量中C++
- 编译错误 - 数组下标'char[int]'的类型无效
- 从“char*”到“char”[-fpermissive]的转换无效,数组下标的类型“char[int]”无效
- 如何在文件中读取,其中包含char, int和空白到链表
- 如何在我的程序中查找"const char* + int"表达式
- While loop and cin char, int
- 如何将输入作为字符串,并将每个字符标识为char, int或float
- 如何正确使用char[int]