C ++代码段执行

时间:2015-12-29 00:52:06

标签: c++ compiler-errors execution

我正在处理过去的试卷,我想知道是否有人可以解释这个问题的解决方案:给出这个(不正确的)代码片段作为头文件。

#include <iostream>
using namespace std;
class Weight
{
public:
    Weight(const int = 0, const int = 0);
    Weight(const int = 0);
    int totalPounds();
    Weight operator+(const Weight);
    Weight operator++();
    Weight operator++(int);
private:
    int stones;
    int pounds
};
void operator<<(ostream& os, const Weight&);

在main方法中执行此操作,并假设.cpp类存在所述头文件的实现。

Weight a(12);
const Weight b(15, 3);
const int FIXED_WEIGHT = b.totalPounds();
Weight combined = a + b;
++a;
b++
combined = 5 + a;
a = b + 1;
cout << a << b;

哪个行会导致头文件出错,以及需要对头文件进行哪些修改?

我真的很困惑,我们在课堂上几乎没有覆盖默认参数...我尝试删除它们使代码工作但我不认为这是解决方案。代码行const int = 0的含义是什么,以及如何基于此实现某些东西。这不会导致模糊定义的构造函数吗?

1 个答案:

答案 0 :(得分:1)

假设在;pounds之后丢失b++是拼写错误,我看到的错误是:

  1. 歧义的构造函数。你只需要第一个。
  2. b是const,因此调用totalPounds失败,因为它不是const方法。
  3. b是const,因此后增量失败,因为它不是const方法。
  4. 5 + a失败,因为没有匹配的+运算符可供使用。
  5. b是const,因此b + 1失败,因为+不是const方法。
  6. void返回operator<<的值会导致cout语句失败。
  7. operator<<(ostream& os, const Weight&)不是朋友,因此无法实际打印Weight的内部值。
相关问题