简体   繁体   中英

What errors do following code have?

I am still a beginner in C++, and I am supposed to find the errors in the following code.

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 };

I understand that in the sixth line there is an error: reference f need to be initialized. But I am confused about the seventh line. It looks like a constructor, but I cannot make sure p = &x; is correct? Also, If I want to correct the error of the reference initialization, how can I do it?

The best thing to do to find out if there are errors is simply to compile it (1) .

If you do that, you'll find at least two problems:

  • references should be initialised; and
  • you can't assign a float-pointer to and int-pointer.

(1) As per this transcript:

$ 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;

is not right since p is of type int* and &x is of type float* .

f = x;

is most likely not what you intended. You probably want to f to be a reference to x . The above line does not do that. It assigns the value of x to the object referenced by f .

If you want f to be a reference to x , you need to initialize it as:

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

Using

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

is problematic since f will be a dangling reference once the function returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM