0

I have two questions about the following code.

class cls{
    int vi;
    public:
        cls(int v=37) { vi=v; }
        friend int& f(cls);
};

int& f(cls c) { return c.vi; }

int main(){
    const cls d(15);
    f(d)=8;
    cout<<f(d);
    return 0;
}
  1. Why does it compile, since f(d) = 8 attemps to modify a const object?
  2. Why does it still print 15, even after removing the const attribute?
4

1 回答 1

6

由于通过值而不是引用传递的参数,它不会修改const对象作为副本。这也是它没有被修改的原因。df()d

于 2012-09-21T10:16:49.670 回答