在C++中继承类时出错:模板参数推导/替换失败

Getting error in inheriting class in C++: template argument deduction/substitution failed

本文关键字:参数 失败 替换 C++ 继承 出错      更新时间:2023-10-16

我是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]

不能将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中的运算符重载即可。

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<<

下面一行表示您正在将void附加到stdout,这是不受支持的。

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

所以编译器抱怨如下。

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

你可以用以下方法做同样的事情,

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

您应该将std::ostream&流参数进入显示功能:

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

然后您可以显示将对象写入标准输出或文件。