简体   繁体   中英

Inaccessible member function when trying to overload << stream as friend?


Problem Solved, thank you all for your help!


I've run into a problem that i can't seem to figure out.

I am trying to overload the ostream operator as a friend function in order to be able to print out the member data of that object, and i can't seem to get it to work.

This is what i got so far:

.h file:

Class TestIt:
{
public:
TestIt();
TestIt(int a, b);

friend ostream& operator <<(ostream& outputStream, const TestIt& a);

Private:
int NUMBER1;
int NUMBER2;
};

.cpp file:

ostream& operator <<(ostream& outputStream, const TestIt& a)
{
 outputStream << a.NUMBER1 << " " << a.NUMBER2;

return(outputStream);
}

What i am trying to do is, pass in an object in ostream, then output its member data. The error that i am receiving is that

"the member TestIt::NUMBER1 declared in TestIt.h is inaccessible.

and same error also exists with my other member data.

Why would that be?

Thank you for your help.


Here's a whole program that i just wrote, giving me the same error:

TestClass.cpp

#include "TestClass.h"
#include <iostream>

using namespace std;

TestClass::TestClass(int a, int b)
{
    age = a;
    whole = b;
}

int TestClass::GetAge() const
{
    return(age);
}

ostream& operator <<(ostream& outputStream, const TestClass& t1)
{
    t1.whole;
    t1.age;

    return(outputStream);
}

TestClass.h

#ifndef TestClass_H
#define TestClass_H

class TestClass
{

public:
    TestClass(int a, int b);
    int GetAge() const;

    friend ostream& operator <<(ostream& outputStream, const TestClass& t1);

private:
    int whole;
    int age;

#endif

The operator<< that you've defined and the operator<< that you've friended aren't the same name. Are you using namespaces?

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