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

时间:2015-07-04 15:47:12

标签: c++ objective-c++

问题出在main我想在set()函数上调用display()函数,该函数返回对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;
}

我只是想知道为什么set('#')无法在display(cout)上调用,而set('#').display(cout)会返回对const的引用。 可以display(cout).set('#')但不能STDIN 一个卑鄙的常数如何对呼叫产生这样的影响?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

如果调用成员函数,则会有一个隐式this指针作为参数传递给函数。在您的情况下,this指针为const,并且无法在set函数内修改。所以它失败了。

相关问题