#include <iostream>
using namespace std;
class Counter
{
protected:
unsigned int count;
public:
Counter ():count ()
{ }
Counter (int c):count (c)
{ }
unsigned int get_count () const
{ return count;}
Counter operator ++ ()
{return Counter (++count);}
};
class CountDn:public Counter
{
public:CountDn ():Counter (){ }
CountDn (int c):Counter (c){ }
CountDn operator -- ()
{return CountDn (--count);}
};
int main ()
{
CountDn c1;
CountDn c2 (100);
cout << "\nc1=" << c1.get_count ();
cout << "\nc2=" << c2.get_count ();
++c1;
++c1;
++c1;
cout << "\nc1=" << c1.get_count ();
--c2;
--c2;
cout << "\n c2=" << c2.get_count ();
CountDn c3 = ++c2;
cout << "\n c3=" << c3.get_count ();
cout << endl;
return 0;
}
当我使用重载'++'运算符时,我得到错误,而当我使用' - '时它运行正常。
错误讯息是
37:14: error: conversion from ‘Counter’ to non-scalar type ‘CountDn’ requested
CountDn c3 = ++c2;
为什么我会收到此错误? 这个错误意味着什么,我该如何解决?
答案 0 :(得分:0)
当我使用重载的&#39; ++&#39;时,我收到错误操作员,当我使用&#39; - &#39;。
时效果很好
您在CountDn类
中实现了 - 但不是++的运算符重载您在CountDn类中缺少++的运算符重载 你必须添加
CountDn operator ++ ()
{return CountDn (++count);}
修改后
#include <iostream>
using namespace std;
class Counter
{
protected:
unsigned int count;
public:
Counter ():count ()
{ }
Counter (int c):count (c)
{ }
unsigned int get_count () const
{ return count;}
Counter operator ++ ()
{return Counter (++count);}
};
class CountDn:public Counter
{
public:CountDn ():Counter (){ }
CountDn (int c):Counter (c){ }
CountDn operator -- ()
{return CountDn (--count);}
CountDn operator ++ ()
{return CountDn (++count);}
};
int main ()
{
CountDn c1;
CountDn c2 (100);
cout << "\nc1=" << c1.get_count ();
cout << "\nc2=" << c2.get_count ();
++c1;
++c1;
++c1;
cout << "\nc1=" << c1.get_count ();
--c2;
--c2;
cout << "\n c2=" << c2.get_count ();
CountDn c3 = ++c2;
cout << "\n c3=" << c3.get_count ();
cout << endl;
return 0;
}
输出
c1=0
c2=100
c1=3
c2=98
c3=99
Program ended with exit code: 0
答案 1 :(得分:0)
的结果
Counter operator ++ ()
{return Counter (++count);}
的类型为Counter
,且无法从Counter
转换为CountDn
。
以下行编译好了:
Counter c3 = ++c2;