2013-08-27 56 views
1

我是C++的新手。在C++中繼承類時出錯:模板參數推導/替換失敗

我寫了一個非常簡單的程序,該程序如下

#include<iostream> 

using namespace std; 

class index 
{ 
protected: 
    int count; 
public: 
    index() 
    { 
     count=0; 
    } 
    index(int c) 
    { 
     count=c; 
    } 
    void display() 
    { 
     cout<<endl<<"count="<<count; 
    } 
    void operator ++() 
    { 
     count++; 
    } 
}; 

class index1:public index{ 
public: 
    void operator --() 
    { 
     count--; 
    } 
}; 

int main() 
{ 
    index1 i; 
    i++; 
    cout<<endl<<"i="<<i.display(); 
    i++; 
    cout<<endl<<"i="<<i.display(); 
    i--; 
    cout<<endl<<"i="<<i.display(); 
} 

但是,當我編譯G ++這段代碼中,我得到這個:

In file included from /usr/include/c++/4.7/iostream:40:0, 
       from inheritance.cpp:1: 
/usr/include/c++/4.7/ostream:480:5: note: template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, char) 
/usr/include/c++/4.7/ostream:480:5: note: template argument deduction/substitution failed: 
inheritance.cpp:40:30: note: cannot convert ‘i.index1::<anonymous>.index::display()’ (type ‘void’) to type ‘char’ 

編輯 我改變cout<<endl<<"i="<<i.display();cout<<endl<<"i="; i.display();它解決了這個問題。

但現在我越來越

inheritance.cpp:39:3: error: no ‘operator++(int)’ declared for postfix ‘++’ [-fpermissive]

+2

您試圖將* void *函數的返回值傳遞給iostream ...您可能意思是'cout << endl <<「i =」; i.display();' – Borgleader

+0

@Borgleader:謝謝,它解決了這個問題。但它找不到我的重載操作符.''繼承。cpp:42:3:錯誤:沒有爲後綴'++'聲明'operator ++(int)'[-fpermissive] ' –

+0

修復後操作符可以通過運算符++(int)語法重載。 – Kunal

回答

2

你不能傳遞一個void功能的iostream

要麼你的功能應該返回一個值或iostreamdisplay()寫自己的東西(就像它似乎是)。您可以通過執行解決你的問題:

int main() 
{ 
    index1 i; 
    i++; 
    cout<<endl<<"i="; 
    i.display(); 
    i++; 
    cout<<endl<<"i="; 
    i.display(); 
    i--; 
    cout<<endl<<"i="; 
    i.display(); 
} 

而且你operator++超載是錯誤的,它應該是:

index operator ++(int) // Look at the return value 
{ 
    count++; 
    return *this;  // return 
} 

operator--同樣的事情。

只要看看this就可以瞭解操作符重載。

0

note:開頭的g ++錯誤消息僅提供了有關爲什麼發生以前的錯誤的更多信息。用g ++ 4.8,我得到(其他錯誤):

main.cpp:40:21: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘void’) 
    cout<<endl<<"i="<<i.display(); 
        ^

這很好的解釋了這個問題。 i.display()的類型是void,所以你不能將它傳遞到operator<<那樣。

0

以下行表示您將void附加到標準輸出並且不支持。

cout<<endl<<"i="<<i.display(); 

所以編譯器抱怨如下。

"cannot convert ‘i.index1::<anonymous>.index::display()’ (type ‘void’) to type ‘char’" 

你可以做以下的相同,

cout<<endl<<"i="; 
i.display(); 
0

你應該把的std :: ostream的&流參數到顯示功能:

std::ostream& display(std::ostream& stream) 
{ 
    stream << endl << "count=" << count; 
    return stream; 
} 

然後你就可以顯示寫將對象轉換爲標準輸出或文件。