2

A is a C++ class written by me:

class A
{
private:
    int _num1;
    int _num2;
public:
    A(int num1, int num2)
    {
        _num1 = num1;
        _num2 = num2;
    }

    ~A(){}

    int getNum1() { return _num1; };
    std::ostream &operator<<(std::ostream &os, A const &obj) { return os << obj.getNum1(); };
};

there is a template's function printArray:

template <class T>
void printArray(T* arr, int size)
{
    int i = 0;
    for (i = 0; i < size; i++)
        cout << arr[i] << endl;
}

When I write in main function:

    A arr4[4] = { A(1,1), A(1,4), A(6,6), A(0,0) };
    printArray(arr4, 4);

there are this errors:

E0344 too many parameters for this operator function.

C2804 binary 'operator <<' has too many parameters.

C2333 'A::operator <<': error in function declaration; skipping function body.

What is the problem and how to fix it?

of course I included iostream

Community
  • 1
  • 1
arik
  • 35
  • 4

1 Answers1

2

You have 2 problems: 1. you should use friend keyword to overload << operator 2. getNum1 should be const

class A
{
private:
    int _num1;
    int _num2;
public:
    A(int num1, int num2)
    {
        _num1 = num1;
        _num2 = num2;
    }

    ~A() {}

    int getNum1() const { return _num1; };
    friend std::ostream &operator<<(std::ostream &os, A const &obj) { return os << obj.getNum1(); };
};
Killzone Kid
  • 6,171
  • 3
  • 17
  • 37