错误:在 C++ 中从“Counter”转换为非标量类型“CountDn”
Posted
技术标签:
【中文标题】错误:在 C++ 中从“Counter”转换为非标量类型“CountDn”【英文标题】:error: conversion from 'Counter' to non-scalar type 'CountDn' in c++ 【发布时间】:2017-08-16 02:40:47 【问题描述】:#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;
为什么会出现此错误? 这个错误是什么意思,我该如何解决?
【问题讨论】:
【参考方案1】:当我使用重载的 '++' 运算符时出现错误,而当我使用 '--' 时效果很好。
您在 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
【讨论】:
【参考方案2】:结果
Counter operator ++ ()
return Counter (++count);
属于Counter
类型,并且没有从Counter
到CountDn
的转换。
以下行编译正常:
Counter c3 = ++c2;
【讨论】:
以上是关于错误:在 C++ 中从“Counter”转换为非标量类型“CountDn”的主要内容,如果未能解决你的问题,请参考以下文章
错误:请求从“const char [5]”转换为非标量类型“String”
在 C++ 中从 size_t 转换/转换为 uint8_t?