1

I'm trying to overload << and >> operators in my Array class. I do it this way:

template<class T>
ostream& operator<<(ostream& out, const Array<T>& a) {
    for (int i = 0; i < a.m_size; i++) {
        out << a.m_data[i] << " ";
    }
    out << endl;

    return out;
}

template<class T>
istream& operator>>(istream& in, Array<T>& a)
{
    cout << "Enter n: ";
    in >> a.m_size;
    a.m_data = new T[a.m_size];

    for (int i = 0; i < a.m_size; i++)
    {
        cout << "Enter a[" << i << "] = ";
        in >> a.m_data[i];
    }
    return in;
}

Is my implementation right? My main() didn't run when I call cout << array or cin >> array

This is class Array:

template<class T>
class Array {
    private:
        int m_size;
        T* m_data;
    public:
        friend ostream& operator<<(ostream& out, const Array<T>& a);
        friend istream& operator>>(istream& in, Array<T>& a);
};

My main() function:

int main()
{
    Array<int> b;
    cin >> b;
    cout << b;
}

Error message:

Error:LNK2019
Severity    Code    Description Project File    Line    Suppression State
Error   LNK2019 unresolved external symbol "class std::basic_istream<char,struct std::char_traits<char> > & __cdecl operator>>(class std::basic_istream<char,struct std::char_traits<char> > &,class Array<int> &)" (??5@YAAAV?$basic_istream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$Array@H@@@Z) referenced in function _main     
Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
Daly
  • 31
  • 4
  • 1
    please provide a [mcve], details do matter. Did you maybe but the template in a source file? – 463035818_is_not_an_ai Jul 14 '20 at 14:15
  • One the one hand, stop with `using namespace std;`. On the other, iterators are much preferred for container-type classes. Did you include ``? Is your class really just what you posted? If so, it's no wonder it breaks. You can immediately go into undefined behavior by manipulating memory you don't own. The expectation that your object is invalid until you invoke the `operator>>()` is bad practice. It's worth learning about the invariant. Echoing @idclev463035818, please post a [mre]. Otherwise you're going lead everyone on a different goose chase due to the missing details. – sweenish Jul 14 '20 at 14:39
  • 1
    The `operator>>` is not supposed to interact with the user in any way. Imagine reading a thousand of these from a file and having to look at all those prompts scroll by. – molbdnilo Jul 14 '20 at 14:43

0 Answers0