可能重载operator *到多个int和一个char *? [英] Possible to overload operator* to multiple an int and a char*?
问题描述
我想获得功能,所以我可以这样做:
I would like to get functionality so I can do this:
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职位中的答案什么'必须有类或枚举类型的参数'实际上意味着什么它几乎看起来像我不能做这一时期。这是真的吗?
According to the answers in this SO post What does 'must have an argument of class or enumerated type' actually mean it almost seems like I can't do this period. Is that really the case? If not, how do I fix this or arrange a workaround?
我知道我可以做的是有 rhs
作为 std :: string
,但是整个练习的一半被放弃,因为 5 * std :: string(\\\
很笨重。
)
What I know I can do is have rhs
as a std::string
, but then the whole point of the exercise is half foregone, as 5*std::string("\n")
is quite clunky.
推荐答案
你应该能够使用用户定义的文字。例如:
You should be able to achive it with user-defined literals. For instance:
#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";
}
这篇关于可能重载operator *到多个int和一个char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!