在 C++ 中将字符串乘以 int

2022-01-14 00:00:00 multiplication string integer c++ cout

当我这样做时,我该怎么做

What do I have to do so that when I

string s = ".";

如果我这样做

cout << s * 2;

会不会一样

cout << "..";

?

推荐答案

不,std::string 没有 operator *.您可以将 (char, string) 添加到其他字符串.看看这个 http://en.cppreference.com/w/cpp/string/basic_string

No, std::string has no operator *. You can add (char, string) to other string. Look at this http://en.cppreference.com/w/cpp/string/basic_string

如果你想要这种行为(没有建议),你可以使用这样的东西

And if you want this behaviour (no advice this) you can use something like this

#include <iostream>
#include <string>

template<typename Char, typename Traits, typename Allocator>
std::basic_string<Char, Traits, Allocator> operator *
(const std::basic_string<Char, Traits, Allocator> s, size_t n)
{
   std::basic_string<Char, Traits, Allocator> tmp = s;
   for (size_t i = 0; i < n; ++i)
   {
      tmp += s;
   }
   return tmp;
}

template<typename Char, typename Traits, typename Allocator>
std::basic_string<Char, Traits, Allocator> operator *
(size_t n, const std::basic_string<Char, Traits, Allocator>& s)
{
   return s * n;
}

int main()
{
   std::string s = "a";
   std::cout << s * 5 << std::endl;
   std::cout << 5 * s << std::endl;
   std::wstring ws = L"a";
   std::wcout << ws * 5 << std::endl;
   std::wcout << 5 * ws << std::endl;
}

http://liveworkspace.org/code/52f7877b88cd0fba4622fab885907313

相关文章