如何修复在C++中使用重载运算符时的二义性错误?

rpppsulh  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(223)

我正在做一个作业,涉及到制作一个程序,交互/修改学校成绩(添加,改变标记)。一些函数将等级从int更改为字母等级,另一个函数则更改为GPA版本(1 - 4)。
以下是作业表上列出的约束条件的摘要:

  • 使用指定的重载运算符
  • 到目前为止,代码中的每个重载运算符都是必需的
      • 提供主. cpp文件;请勿修改。**
  • 根据指示返回类型

除了执行到main()中的最后两个语句之外,我的代码还能正常工作:

  1. cout << (val += n) << endl;
  2. cout << (val += k) << endl;

我得到了这些错误:

  1. more than one conversion function from "sdds::Mark" to a built-in type applies:
  2. function "sdds::Mark::operator int()" (declared at line 17 of "/Users/...)
  3. function "sdds::Mark::operator double()" (declared at line 21 of "/Users/..)
  4. function "sdds::Mark::operator char()" (declared at line 22 of "/Users/..)
  5. more than one conversion function from "sdds::Mark" to a built-in type applies:
  6. (same as above)
    • 如何在不修改main的情况下修复歧义?* * 顺便说一句,注解是我从作业单上复制的一些说明,但不是所有的说明都在注解中。
    • Main. cpp**
  1. #include <iostream>
  2. #include "Mark.h"
  3. using namespace std;
  4. using namespace sdds;
  5. int main()
  6. {
  7. Mark n(25), k(200);
  8. int val = 60;
  9. cout << "int += Mark ..." << endl;
  10. cout << (val += n) << endl;
  11. cout << (val += k) << endl;
  12. return 0;
  13. }
    • 标记. h**
  1. namespace sdds {
  2. class Mark
  3. {
  4. int markVal;
  5. void setEmpty();
  6. public:
  7. Mark();
  8. Mark(int val);
  9. bool markIsValid();
  10. operator int();
  11. Mark &operator+=(int addVal);
  12. Mark &operator=(int newMark);
  13. operator double();
  14. operator char();
  15. };
  16. }

*CORRECT * 最后两行输出(不是我的):

  1. int += Mark
  2. 140
  3. 140
hivapdat

hivapdat1#

正如已经说过的那样,声明所有的转换算子都是显式的:

  1. explicit operator int();
  2. explicit operator double();
  3. explicit operator char();

然后添加重载的operator+=,该int位于左手:

  1. Mark& operator+=(int addVal, const Mark &);

你会得到进一步的错误:

  1. error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'sdds::Mark')

您需要重载流输出操作符:

  1. std::ostream& operator<<(std::ostream& out, const Mark& m) {
  2. out << static_cast<T>(m); // pick the type T
  3. return out;
  4. }

或转换总和:

  1. std::cout << static_cast<T>(val += k) << std::endl; // pick the type T

我得到了什么

  1. #include <iostream>
  2. namespace sdds {
  3. class Mark
  4. {
  5. int markVal;
  6. void setEmpty();
  7. public:
  8. Mark();
  9. Mark(int val);
  10. bool markIsValid();
  11. Mark &operator+=(int addVal);
  12. Mark &operator=(int newMark);
  13. explicit operator int();
  14. explicit operator double();
  15. explicit operator char();
  16. };
  17. Mark& operator+=(int addVal, Mark &);
  18. std::ostream& operator<<(std::ostream& out, Mark& m) {
  19. out << static_cast<int>(m); // pick the type T
  20. return out;
  21. }
  22. }
  23. int main()
  24. {
  25. sdds::Mark n(25);
  26. int val = 60;
  27. std::cout << "int += Mark ..." << std::endl;
  28. std::cout << (val += n) << std::endl;
  29. return 0;
  30. }
展开查看全部

相关问题