C++ 代码片段执行
C++ Code Snippet 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 class 与所述头文件的实现一起存在。
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;
哪一行会导致头文件出错,需要对头文件进行哪些修改?
我真的很困惑,我们几乎没有涵盖 class 中的默认参数...我尝试删除它们使代码工作,但我认为这不是解决方案。另外,代码行 const int = 0
是什么意思,我将如何基于它来实现某些东西。这不会导致构造函数定义不明确吗?
假设 pounds
和 b++
之后缺少的 ;
是错别字,我看到的错误是:
- 构造函数不明确。你只需要第一个。
b
是常量,因此调用 totalPounds
失败,因为它不是常量方法。
b
是常量,所以 post-increment 失败,因为它不是常量方法。
5 + a
失败,因为没有匹配的 +
运算符可供使用。
b
是常量,因此 b + 1
失败,因为 +
不是常量方法。
void
return operator<<
的值导致 cout
语句失败。
operator<<(ostream& os, const Weight&)
不是朋友,所以无法实际打印 Weight
. 的内部值
我正在研究过去的试卷,我想知道是否有人可以解释这个问题的解决方案:假设这个(不正确的)代码片段是一个头文件。
#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 class 与所述头文件的实现一起存在。
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;
哪一行会导致头文件出错,需要对头文件进行哪些修改?
我真的很困惑,我们几乎没有涵盖 class 中的默认参数...我尝试删除它们使代码工作,但我认为这不是解决方案。另外,代码行 const int = 0
是什么意思,我将如何基于它来实现某些东西。这不会导致构造函数定义不明确吗?
假设 pounds
和 b++
之后缺少的 ;
是错别字,我看到的错误是:
- 构造函数不明确。你只需要第一个。
b
是常量,因此调用totalPounds
失败,因为它不是常量方法。b
是常量,所以 post-increment 失败,因为它不是常量方法。5 + a
失败,因为没有匹配的+
运算符可供使用。b
是常量,因此b + 1
失败,因为+
不是常量方法。void
returnoperator<<
的值导致cout
语句失败。operator<<(ostream& os, const Weight&)
不是朋友,所以无法实际打印Weight
. 的内部值