简体   繁体   中英

Operator << Overload and Const References

I have a class with a char * as private member data. I'm passing in an object of the class to an operator overload of <<. If I don't use a const reference, I get an error stating that the char * is private member data. If I use a const reference, this error goes away.

Is private member data accessible when an object is passed by const reference and not when it is passed by reference?

Code:

// .h file
#include <iostream>
using namespace std;

class Flex
{  
    // The error was caused by having a const in the definition 
    // but not the declaration 
    // friend ostream& operator<<( ostream& o, const Flex& f );  

    // This fixed it
    friend ostream& operator<<( ostream& o, Flex& f );

    public:

    Flex();
    Flex( const char * );
    ~Flex();

    void cat( const Flex& f );

    private:

    char * ptr;
};

// .cpp file
#include <iostream>
#include <cstring>
#include "flex.h"
using namespace std;

Flex::Flex()
{
    ptr = new char[2];

    strcpy( ptr, " ");
}

Flex::Flex( const char * c )
{
    ptr = new char[strlen(c) + 1];

    strcpy( ptr, c );
}

Flex::~Flex()
{
    delete [] ptr;
}

void Flex::cat( const Flex& f )
{
    char * temp = ptr;

    ptr = new char[strlen(temp) + strlen(f.ptr) + 1];

    strcpy( ptr, temp );

    delete [] temp;

    strcat( ptr, f.ptr );
 }

ostream& operator<<( ostream& o, Flex& f )
{
    o << f.ptr;

    return 0;
}

// main.cpp
#include <iostream>
#include "flex.h"

using namespace std;

int main()
{

    Flex a, b("one"), c("two");

    b.cat(c);

    cout << a << b << c;

    return 0;

}

Is private member data accessible when an object is passed by const reference and not when it is passed by reference?

Visibility and const ness are orthogonal concepts. You can access private members through a const reference.

You were quite unclear as to what the actual error you're getting is, or what the real problem is. However, I'm guessing you have implemented a free operator<<(ostream&, const MyClass&) function which somehow attempts to modify MyClass::ptr (or some other member variable).

If so, that won't work because the reference is const . Don't modify it's members.

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