【问题标题】:What errors do following code have?以下代码有什么错误?
【发布时间】:2015-10-19 01:02:05
【问题描述】:

我还是个C++初学者,应该能在下面的代码中找到错误。

1 class Thing
2 {
3    public:
4       char c;
5       int *p;
6       float& f;
7       Thing(char ch, float x) { c = ch; p = &x; f = x; }
9 };

我明白第六行有一个错误:reference f需要被初始化。但我对第七行感到困惑。它看起来像一个构造函数,但我不能确定 p = &x;是正确的?另外,如果我想纠正引用初始化的错误,我该怎么做?

【问题讨论】:

  • 你已经差不多了。现在您只需要继续思考和研究以发现如何初始化引用,就完成了。

标签: c++ class pointers reference


【解决方案1】:

找出是否有错误最好的办法就是编译它(1)

如果你这样做,你会发现至少有两个问题:

  • 应该初始化引用;和
  • 您不能将浮点指针分配给整数指针。

(1) 根据这份成绩单:

$ g++ -c -o prog.o prog.cpp
prog.cpp: In constructor ‘Thing::Thing(char, float)’:
prog.cpp:7:7: error: uninitialized reference member in ‘float&’ [-fpermissive]
       Thing(char ch, float x) { c = ch; p = &x; f = x; }
       ^
prog.cpp:6:14: note: ‘float& Thing::f’ should be initialized
       float& f;
              ^
prog.cpp:7:43: error: cannot convert ‘float*’ to ‘int*’ in assignment
       Thing(char ch, float x) { c = ch; p = &x; f = x; }
                                           ^

【讨论】:

  • 既然这里的x: Thing(char ch, float x) 是传值的,我还能访问x的地址吗?
  • @Aria,不,当您清理每个问题并尝试重新编译时,这一点会变得清晰 :-) 对象x,作为一个形式参数而不是实际参数,一旦函数消失,它将消失返回,因此设置对它的引用,它本身将在函数退出中幸存下来是不行的。
【解决方案2】:
p = &x;

不正确,因为p 的类型为int*,而&x 的类型为float*

f = x;

很可能不是您想要的。您可能希望 f 成为对 x 的引用。上面的行没有这样做。它将x 的值分配给f 引用的对象。

如果您希望f 成为对x 的引用,则需要将其初始化为:

Thing(char ch, float& x) : f(x) { ... }
               //  ^^^ different from your signature

使用

Thing(char ch, float x) : f(x) { ... }

这是有问题的,因为一旦函数返回,f 将是一个悬空引用。

【讨论】:

  • 我可以改变这一行吗: Thing(char ch, float x) { c = ch; p = &x; f = x; } in to Thing(char ch, float x) { c = ch; &f = x; },还要删除第六行?
  • 不,你不能。您的问题使我确信您不了解 C++ 中的引用类型是如何工作的。试试stackoverflow.com/questions/2765999/…
猜你喜欢
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多