我正在处理过去的试卷,我想知道是否有人可以解释这个问题的解决方案:给出这个(不正确的)代码片段作为头文件。
#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
的含义是什么,以及如何基于此实现某些东西。这不会导致模糊定义的构造函数吗?
答案 0 :(得分:1)
假设在;
和pounds
之后丢失b++
是拼写错误,我看到的错误是:
b
是const,因此调用totalPounds
失败,因为它不是const方法。b
是const,因此后增量失败,因为它不是const方法。5 + a
失败,因为没有匹配的+
运算符可供使用。b
是const,因此b + 1
失败,因为+
不是const方法。void
返回operator<<
的值会导致cout
语句失败。operator<<(ostream& os, const Weight&)
不是朋友,因此无法实际打印Weight
的内部值。