operator overloading syntax

I am not really sure if this is correct. Obviously not as i get an error. I more or less googled the process on how to overload an operator, and found myself in more deep than i was expecting. Essentially i was trying to multiple a string: so the string object would multiply by the integer given

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

class String{
    public:
        std::string str;
        
        String(std::string string){
            str = string;
        }
    
        std::ostream& operator*(int num){
            std::string s;
            for (int i=0; i<num; i++){
                s += this->str;
            }
            return s;
        }
};


int main(){
    String test("tester");
    std::cout << test * 3;
}


My expected outcome would be:
testertestertester

I am not really sure on how to interpret the error code:
1
2
3
4
test2.cpp: In member function ‘std::ostream& String::operator*(int)’:
test2.cpp:21:20: error: invalid initialization of reference of type ‘std::ostream& {aka std::basic_ostream<char>&}’ from expression of type ‘std::string {aka std::basic_string<char>}’
             return s;
                    ^
Last edited on
You are so close!

change line 15:
std::ostream& operator*(int num){
to
std::string operator*(int num){

So the output of the function is a string. That string then goes into the cout. YOu don't need to output cout.
ah, ok

thank you very much Stewbond.
You don't need to wrap the string class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

std::string operator*(std::string lhs, int rhs)
{
    std::string s;
    
    for (int i = 0; i < rhs; i++)
    {
        s += lhs;
    }
    
    return s;
}

int main()
{
    std::string s = "tester";
    
    std::cout << s * 3;
    
    return 0;
}

// testertestertester 
Not a good idea making new operators to work on standard library types: they cannot be found by name lookup from within standard algorithms. Making your own wrapper class as in OP's class String, is better.
Topic archived. No new replies allowed.