Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : error: invalid operands of types ‘String*’ and ‘const char [7]’ to binary ‘operator+’

I'm learning cpp and In my last assignment I am rewriting the std::string class. so here is an outline of my code: string class:

   class String {
    public:
        String(const char* sInput) {
            string = const_cast<char*> (sInput);                
        }

        const String operator+(const char* str) {
            //snip
            print();
        }

        void print() {
            cout<<string;
        }

        int search(char* str) {

        }

    private:
        char* string;
        int len;
};

Oh and I have to say I tried to declare the method as String* operator+(const char* str) and as const String& operator+(const char* str) with no change. And here is how I run it:

int main(int argc, char* argv[]) {
    String* testing = new String("Hello, "); //works
    testing->print();//works
    /*String* a = */testing+"World!";//Error here.
return 0;
}

The full error goes like such:

foobar.cc:13: error: invalid operands of types ‘String*’ and ‘const char [7]’ to binary ‘operator+’

I looked up on Google and in the book I am learning from with no success. any one with suggestions? (I am pretty sure I am doing something foolish you will have to forgive me I am originally a PHP programmer) can any one point me to what am I missing?

like image 695
Leon Fedotov Avatar asked Feb 28 '23 09:02

Leon Fedotov


2 Answers

You probably don't want to use a pointer to your String class. Try this code:

int main(int argc, char* argv[]) {
    String testing = String("Hello, "); //works
    testing.print();//works
    String a = testing+"World!";
    return 0;
}

When defining new operators for C++ types, you generally will work with the actual type directly, and not a pointer to your type. C++ objects allocated like the above (as String testing) are allocated on the stack (lives until the end of the "scope" or function) instead of the heap (lives until the end of your program).

If you really want to use pointers to your type, you would modify the last line like this:

String *a = new String(*testing + "World!");

However, following the example of std::string this is not how you would normally want to use such a string class.

like image 187
Greg Hewgill Avatar answered Apr 28 '23 04:04

Greg Hewgill


Your operator+ is defined for String and const* char, not for String*. You should dereference testing before adding it, i.e.:

String a = (*testing) + "World";

Though in this case I don't see the point in making testing a pointer in the fist place.

Edit: Creating a string without pointers would look like this:

String testing = "Hello, ";

or

String testing("Hello, ");

(both are equivalent).

like image 36
sepp2k Avatar answered Apr 28 '23 02:04

sepp2k