简体   繁体   中英

c++ ostream return data from objects array

I've the following source code for my ostream

ostream& operator << (ostream& os, AnimalsDirectory& a) {
   for(int i=0;i<a.directorySize;i++) {
      return os << a.animals[i];
   }
}

When I compile this code it produces me the following error:

ContactDir.cpp:64:1: warning: control may reach end of non-void 
function
  [-Wreturn-type]
}
^

I don't know why this error occurs, I do it on objects animals array and want '<<' print all info about what this array has. Thanks in advance!

Have a look how the operator method you want to implement is declared. You have to return a reference to a ostream object which is the one you get in your first parameter.

Secondly you have a return statement in your loop which will quit the function in the first loop cycle. What you probably want to do is something like this

ostream& operator << (ostream& os, AnimalsDirectory& a) {
    for(int i=0;i<a.directorySize;i++) {
       os << a.animals[i];
    }
    return os;
}

This requires that each animal object has also the <<-operator implemented

   for(int i=0;i<a.directorySize;i++) {
      return os << a.animals[i];
   }

Let's see.. what if a.directorySize == 0 ?, then i < a.directorySize is false for i = 0 which means the loop never runs, which means the return statement will not be reached. This invokes undefined behavior as there is nothing to return after the loop. For this the compiler issues a warning.

Furthermore, your code looks odd to say the least, you usually never loop only to unconditionally return.

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