c++ - 使用 cout 运算符重载字符串

标签 c++ string overloading cout

我正在尝试使 << 过载当它收到 string 时.我想要如果 string可以说 Mark , 它会打印 Dog .我知道这对你没有意义,但这就是我需要的。 我已经试过了,但它不起作用。

std::ostream& operator << (std::ostream &out, string& a);
std::ostream& operator << (std::ostream &out, string& a){
     std::cout << "I love dogs";
     return out;
}

int main(){
    std::cout<<"I love cats";
    return 0;
}

我希望它改变每一个string无论我在哪里使用函数 std::cout <<字符串并让它打印出什么 String也就是说,它总是会打印 Dog反而。

我的问题是,而不是打印 Dog , 它继续打印 string给出。就像它不断打印I love cats而不是 I love dogs

我已经试过了:

std::ostream& operator << (std::ostream &out, const char* a){
    std::cout << "I love dogs";
   return out;
}

相反,它给了我段错误。

std::ostream& operator << (std::ostream &out, const char* &a);

而且这个一直在打印I love cats

最佳答案

您必须确保您的自定义 operator<<将调用默认运算符而不是调用自身。您可以通过在重载运算符 (std::operator<<) 上使用命名空间限定符来执行此操作。此外,字符串文字是 const char []而不是 std::string .

#include <iostream>

std::ostream &operator<<(std::ostream &os, const char *) {
  return std::operator<<(os, "I love dogs\n");
}

int main() {
  std::cout << "I love cats\n";
}

关于c++ - 使用 cout 运算符重载字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59346872/

相关文章:

c++ - 如何根据模板参数包是否与函数参数匹配来控制模板函数定义?

Groovy 运算符重载增量/减量错误

c++ - OpenCV 中的 channel 顺序

c++ - 如何从 Python 使用 OpenCV 的 C++ 函数?

c++ - boost 随机数 - 奇怪的编译错误

string - 将cmdlet设置为变量而无需立即调用它

java - 如何解析计算器项目中的操作数和运算符?

c++ - 在返回 void 的函数中调用返回 void 的函数的 return 语句

c - 为什么代码不反转字符串?

c++ - 重载括号 C++ 是个好主意