Trouble with ostream operator overloading

Hi I am fairly new to C++ operator overloading, and I just have one question about it.

So my function:

ostream &operator<<(ostream &out, className &n){
out<<n.variable<<endl;
}

this works, however I need to also cout an array that is from my driver. When I did this without operator overloading I simply passed the array from driver to the function as a parameter like so:

void className::displayInfo(string array[]){
cout<<array[0]<<endl;
}

My question is how would I get my ostream operator overloaded function to have access to the array from my driver file?

I have tried adding parameters to the overloaded function like so:

ostream &operator<<(ostream &out, className &n, string array[]){
out<<n.variable<<array[0]<<endl;
}

and I called the function like this:

className object;
string driverArray;

cout<<object(driverArray);

this gives me the error: "function only takes two arguments". Please help, it would much appreciated!
I don't think it is a good idea to pass an array by value to a function (even if custom one).
The problem of managing an "undefined size" array is that your class cannot control the actual size of the array and if element [x] exists or not.

So it would be better to pass a std::string (if it an array of character) or a std::vector (if it is an array of data).

The syntax would be (taking an example of vector of integers)

1
2
3
4
5
6
7
8
9
ostream &operator<< (ostream &os, const std::vector<int> &val) {
   //your code here
  return os;
}

ostream &operator<< (ostream &os, const ClassName &n) { 
  //your code here
  return os;
}


if you declare those functions you be able to use

out<<val<<n<<endl
Thank you so much for replying, but I just have a question regarding your answer. I already made the array for my program, it has a defined size of 10 and it is filled with values. The only way for my program to work is for me to use this array with the operator<< function. can I do the same thing you suggested with vectors with an array?

This is a program for my class and my professor requires that we do not use vectors yet. thank you again for your help.
> can I do the same thing you suggested with vectors with an array?

Pass the array by reference to the overloaded operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>

template < std::size_t N > // N is the number of elements in the array
std::ostream& operator<< ( std::ostream& stm, const std::string (&ref_to_array)[N] )
{
    stm << "[ " ;
    for( const std::string& s : ref_to_array ) stm << '"' << s << '"' << ' ' ;
    return stm << ']' ;
}

int main()
{
    std::string a[] = { "ab", "cdef", "ghijklmno", "pqrst", "uvwxyz" } ;
    std::cout << a << '\n' ;
}


http://liveworkspace.org/code/3ww0YN$0
Topic archived. No new replies allowed.