簡體   English   中英

重載+ =運算符時無效的操作數錯誤

[英]Invalid operands error while overloading the += operator

句子課

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

實施(不正確,只是測試是否可行)

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

測試操作員

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 ++編譯器錯誤

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*)â

我究竟做錯了什么? 因為從技術上講這應該起作用。 由於左值是指向類對象的指針,而右值是char數組。 所以我很確定操作數不是無效的...

編輯/更新:原型

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

履行

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

您的函數需要一個指針,而不是對象。 只是參考一下( sentence& 。)

順便說一句,您的操作員應該返回參考,而不是副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM