the problem is in main
where I want to call set()
function on display()
function which return a reference to const.
#include "stdafx.h"
#include "iostream"
#include "string"
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::ostream;
class screen
{
public:
typedef string::size_type pos;
screen() = default;
screen(pos ht, pos wd, char c) :height(ht), width(ht),contents(ht*wd, c){}
screen(pos ht, pos wd) :height(ht), width(wd), contents(ht*wd, ' '){}
char get()const{ return contents[cursor]; }
inline char get(pos r, pos c)const;
screen &move(pos r, pos c);
screen &set(char);
screen &set(pos r, pos c,char);
const screen& display(ostream &os)const;
pos cursor;
pos height, width;
string contents;
};
const screen& screen::display(ostream &os)const
{
os<< contents;
return *this;
}
char screen::get(pos r, pos c)const
{
pos row = r*width;
return contents[row + c];
}
screen& screen::move(pos r, pos c)
{
pos row = r*width;
cursor = row + c;
return *this;
}
screen& screen::set(char c)
{
contents[cursor] = c;
return *this;
}
screen& screen::set(pos r, pos c, char ch)
{
pos row = r*width;
contents[row + c] = ch;
return *this;
}
int main()
{
screen myscreen(50, 50,'0');
myscreen.display(cout).set('#');//the problem is here!
return 0;
}
I just want to know why set('#')
cannot be called on display(cout)
which returns a reference to const.
It is possible to set('#').display(cout)
but not display(cout).set('#')
How constness of an abject can have such a effect on a call?
If you call a member function, there is an implicit this
pointer passing as a parameter to the function. In your case, the this
pointer is const
, and it can't be modified inside your set
function. So it failed.