const在函数名c ++之前的参数vs之前 [英] const before parameter vs const after function name c++

查看:96
本文介绍了const在函数名c ++之前的参数vs之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样的东西之间有什么区别

What is the difference betweeen something like this

friend Circle copy(const Circle &);

和类似这样的

friend Circle copy(Circle&) const;

我知道const函数用于告诉编译器这个函数不会尝试改变

I know const after the function is used to tell the compiler that this function won't attempt to change the object it is called on, what about the other one?

推荐答案

第一种形式意味着(状态) code> Circle 绑定到引用的对象是 copy()函数的参数,不会被 copy()。引用是对 const 的引用,因此将无法通过该引用调用 Circle 的成员函数它们本身不符合 const

The first form means that the (state of the) Circle object bound to the reference which is the parameter of the copy() function won't be altered by copy() through that reference. The reference is a reference to const, so it won't be possible to invoke member functions of Circle through that reference which are not themselves qualified as const.

另一方面,第二种形式是非法的: strong>成员函数可以 const -qualified(当你声明有一个全局朋友函数)。

The second form, on the other hand, is illegal: only member functions can be const-qualified (while what you are declaring there is a global, friend function).

const 限定成员函数时,限定条件指的是隐式 this 参数。换句话说,该函数不允许改变被调用的对象的状态(由隐式 this 指针指向的对象) - 除了 mutable 对象,但这是另一个故事。

When const qualifies a member functions, the qualification refers to the implicit this argument. In other words, that function will not be allowed to alter the state of the object it is invoked on (the object pointed to by the implicit this pointer) - with the exception of mutable objects, but that's another story.

用代码说:

struct X
{
    void foo() const // <== The implicit "this" pointer is const-qualified!
    {
        _x = 42; // ERROR! The "this" pointer is implicitly const
        _y = 42; // OK (_y is mutable)
    }

    void bar(X& obj) const // <== The implicit "this" pointer is const-qualified!
    {
        obj._x = 42; // OK! obj is a reference to non-const
        _x = 42; // ERROR! The "this" pointer is implicitly const
    }

    void bar(X const& obj) // <== The implicit "this" pointer is NOT const-qualified!
    {
        obj._x = 42; // ERROR! obj is a reference to const
        obj._y = 42; // OK! obj is a reference to const, but _y is mutable
        _x = 42; // OK! The "this" pointer is implicitly non-const
    }

    int _x;
    mutable int _y;
};

这篇关于const在函数名c ++之前的参数vs之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆