在C++中继承类时出错:模板参数推导/替换失败
Getting error in inheriting class in C++: template argument deduction/substitution failed
我是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
。
函数应该返回一个值,或者iostream
或display()
给自己写一些东西(就像看起来一样)。你可以通过以下操作来解决你的问题:
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;
}
然后您可以显示将对象写入标准输出或文件。
相关文章:
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 视图中的参数推导失败:take_while
- variadic模板中的模板参数推导失败
- 当给定默认值时,为什么此模板参数推导失败
- 模板参数推导失败,函数参数/参数不匹配
- 为什么模板参数推导失败?
- 嵌套参数包扩展失败
- 模板参数的 C++ 自动模板推导失败
- 调试模板时出现问题.专门针对 Linux GCC 7、GCC 6、GCC 5、GCC 4.9 错误构建失败:模板参数 1
- 使用显式模板参数列表和 [temp.arg.explicit]/3 的函数调用的演绎失败
- 失败,出现错误 87:参数不正确.如何判断哪个参数不正确?
- 在 g++ 6.2.1 中将参数包转发到 constructor() 失败
- 当变量和参数名称匹配时,移动语义构造失败
- 作为模板参数的成员函数指针在继承的成员函数上失败,如何以及为什么?
- 模板参数推导/替换失败,lambda作为函数指针
- 为什么在 std::transform 中使用函数对象参数失败并且需要 lambda 表达式
- C++模板参数失败,不是从错误派生的
- CreateThread参数失败
- 在CreateProcess中传递命令行参数失败