gpt4 book ai didi

c++ - 以下代码有什么错误?

转载 作者:行者123 更新时间:2023-11-28 00:10:51 25 4
gpt4 key购买 nike

我还是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 needed be initialized。但是我对第七行感到困惑。它看起来像一个构造函数,但我不能确定 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; }
^

关于c++ - 以下代码有什么错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33205067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com