Zera42
Zera42

Reputation: 2692

Invalid operands error while overloading the += operator

sentence class

class sentence
{   
    public:
        sentence(); 
        ~sentence();
        void testing(sentence *& s);
        sentence operator+=(char * sentence_to_add);
    protected:
        node * head;
};

Implementation (its not correct, just testing if it works)

sentence sentence::operator+=(char * sentence_to_add) 
{
    cout << "testing" << endl;
    return *this;
}

Testing said operator

void sentence::testing(sentence *& s)
{
    char * test_string = new char[5000];
    cout << "please enter a string: " << endl;
    cin.getline(test_string, 5000, '\n');
    s += test_string;
}

G++ compiler error

sentence.cpp: In member function âvoid sentence::testing(sentence*&)â:
sentence.cpp:124:7: error: invalid operands of types âsentence*â and âchar*â to binary âoperator+â
sentence.cpp:124:7: error:   in evaluation of âoperator+=(class sentence*, char*)â

What am I doing wrong? Because technically this should work. Since the lvalue is the pointer to class object, and the rvalue is the char array. So I'm pretty sure the operands are not invalid...

edit/update: prototype

sentence & operator+=(const char * sentence_to_add);

implementation

sentence & sentence::operator+=(const char * sentence_to_add) 
{
    cout << "testing" << endl;
    return *this;
}

Upvotes: 1

Views: 590

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124642

Your function takes a pointer, not an object. Just take a reference (sentence&.)

As an aside, your operator(s) should return a reference, not a copy.

Upvotes: 2

Related Questions