-2

I was looking into how to use operator overloading in c++ to work with classes but could not get a clear idea online so I'm posting this question.I want to basically overload the minus "-" operator to remove a sub-string from a bigger string, . Example is the first string is "Hello World" and the second string is "He", the output should be "llo World".

slowjoe44
  • 7
  • 3
  • 1
    _could not get a clear idea online_ Did you even try looking for tutorials on this subject? Since I, sincerely, doubt, that you couldn't find _anything_. Also, what did you try? Without [mcve] of your attempt - this looks like _write the code for me_ request. – Algirdas Preidžius Mar 14 '17 at 15:51
  • @AlgirdasPreidžius Its not that, just a matter of not being able to use the right terminology to find what i'm looking for since I am a newbie to c++ and just moved onto classes. I just want to learn the basic syntax and idea to it. But thanks anyway mate. – slowjoe44 Mar 14 '17 at 15:57
  • What is the real problem? Operator- overloading **OR** substring removal? For the first one look at [this post](http://stackoverflow.com/questions/4421706/operator-overloading) – Yuriy Ivaskevych Mar 14 '17 at 16:01
  • 1
    @slowjoe44 Googling for _c++ operator overloading tutorial_ gives you plenty of potential answers - meaning, you did not do any research before asking on SO, and, as your current "question" stands - it's too broad, and/or unclear, about what, exactly, you are asking about. – Algirdas Preidžius Mar 14 '17 at 16:02
  • 1
    @slowjoe44 You are asking for two things. How to overload `-`, and how to remove characters from a string. Why not work on the removal of characters first? – PaulMcKenzie Mar 14 '17 at 16:03

1 Answers1

0

Try the following:

#include <iostream>
#include <string>
using namespace std;

//prototype
string operator-(string, const string &);

int main()
{
    cout << "Hello World" - "He" << endl;
}

string operator-(string firstOp, const string &secondOp)
{
    //test if the firstOp contains the secondOp
    if (firstOp.find(secondOp) != string::npos)
    {
        //erase the secondOp of the firstOp
        firstOp.erase(firstOp.find(secondOp), secondOp.length());
    }
    return firstOp;
}

//Output: "llo World"

In here, you declare a global Operator function for the - Operator of class string. When the Compiler finds a '-' he Looks for Operator functions or method, which fit to the given signature (here: const string &, const string &). Hope i could help you :)

Zonico
  • 192
  • 1
  • 11