[英]What errors do following code have?
我仍然是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 };
我知道在第六行有一个错误:引用f需要初始化。 但是我对第七行感到困惑。 它看起来像一个构造函数,但我不能确保p =&x;。 是正确的? 另外,如果我想更正引用初始化的错误,该怎么办?
找出是否有错误的最佳方法就是简单地对其进行编译(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; }
^
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
将成为悬挂的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.