为什么我们不能在 const 对象上调用函数?

sae*_*asi 2 c++ objective-c++

问题在于main我想在返回 const 引用的函数set()上调用函数。display()

#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;
}
Run Code Online (Sandbox Code Playgroud)

我只是想知道为什么set('#')不能调用display(cout)它返回对 const 的引用。有可能,set('#').display(cout)但不可能display(cout).set('#') 一个 abject 的常量如何对调用产生这样的影响?

Sam*_*tep 5

我建议您阅读更多有关constC++ 中具体含义的内容。的总体目的const是防止对象被修改,因此由于非const方法有可能修改对象,因此不能在对象const或const对象的引用上调用它们。

  • 哦,我刚刚意识到,是的,“this 指针”是 const,并想对其调用 set 并更改它。 (2认同)