Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does that casting work?

Tags:

c++

I'm doing an exercise for my uni class. I've stumbled upon a following line of code:

std::cout << (const MaszynaStanow&)m << std::endl;

where m is an object of a class.

It doesn't compile. I assume it's some kind of a casting of an object to a constant reference, right?

I've also written an operator function for "<<" overloading so that I could print out the values held by an object like so:

std::cout << m;

I'm getting the following error upon compilation:

.main.cpp:41:13: error: invalid operands to binary expression('ostream'(aka 'basic_ostream<char>') and 'const MaszynaStanow')
std::cout << (const MaszynaStanow&)m << std::endl;
~~~~~~~~~ ^  ~~~~~~~~~~~~~~~~~~~~~~~

Which makes me think that my operator overloading function is not suitable in this case(?)

ostream & operator<<(ostream & stream, MaszynaStanow & obj){
    cout<<"MaszynaStanow:"<<endl;
    for (int i = 0; i < obj.size; ++i){
        stream <<i<<" "<<obj.Next[i]->returnName();
        if (i == obj.chosenMode) cout <<" <";
        cout<<endl;
    }
    return stream;
}

I would appreciate any kind of help- even a small hint.

like image 736
Static.Mike Avatar asked Apr 18 '26 06:04

Static.Mike


1 Answers

You cast explicitly to a const, but your operator is only able to work with non-const instances of MaszynaStanow. Your operator should have the following form:

ostream & operator<<(ostream & stream, const MaszynaStanow & obj)
                                       ^^^^^
                                       you missed this

If you need the object to be modifiable, keep the current version and do not cast the object to a const one. Although I would not expect operator<< to modify its right-handled operand, so the const should be probably there.

like image 138
Mateusz Grzejek Avatar answered Apr 19 '26 19:04

Mateusz Grzejek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!