Diego Esquivel
Diego Esquivel

Reputation: 194

Overloading string with cout operator

I'm trying to overload the << when it receives a string. I want that if the string is lets say Mark, it prints instead Dog. I know it doesn't make sense for you but this is what I need. I've tried this but it does not work.

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;
}

I want it to change every single string no matter where I use the function std::cout << string and for it to instead printing what String is, it would always print Dog instead.

My problem is that instead of printing Dog, it keeps on printing the string given. Like it keeps printing I love cats instead of I love dogs

I already tried:

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

Instead but it give me segmentation fault.

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

And this one keeps on printing I love cats

Upvotes: 0

Views: 4519

Answers (2)

Gregorio Alonso
Gregorio Alonso

Reputation: 1

You should embrace your code with a namespace std for a properly defined operator<<(...) method for iostream.

#include <iostream>

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

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

Upvotes: 0

Indiana Kernick
Indiana Kernick

Reputation: 5331

You have to ensure that your custom operator<< will call the default operator and not call itself. You can do this by using a namespace qualifier on the overloaded operator (std::operator<<). Also, string literals are const char [] and not 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";
}

Upvotes: 1

Related Questions