C++代码段执行

C++ Code Snippet Execution

本文关键字:执行 代码 段执行 C++      更新时间:2023-10-16

我正在写过去的一篇试卷,我想知道是否有人能解释这个问题的解决方案:考虑到这个(不正确的)代码片段是一个头文件。

#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&);

在主方法中执行,并假设.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的含义是什么,以及我将如何实现基于它的东西。这不会导致定义不明确的构造函数吗?

假设poundsb++之后缺少的;是打字错误,我看到的错误是:

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