注册 登录
编程论坛 C++教室

const修饰函数体的问题?

吉姆汤 发布于 2021-09-07 08:47, 2895 次点击
const修饰函数体,就是在函数后面加个const,是不是只用在类对象里面?
1 回复
#2
rjsp2021-09-07 10:46
只能用在 类成员函数 后面,用于修饰此成员函数,它其实限定的是this指针。

程序代码:
#include <iostream>
#include <source_location>
using namespace std;

struct foo
{
    void bar()          { clog << source_location::current().function_name() << '\n'; }
    void bar() const    { clog << source_location::current().function_name() << '\n'; }
    void bar() volatile { clog << source_location::current().function_name() << '\n'; }
};

int main( void )
{
    foo f;
    const foo cf;
    volatile foo vf;

    f.bar();  // 输出 void foo::bar()
    cf.bar(); // 输出 void foo::bar() const
    vf.bar(); // 输出 void foo::bar() volatile
}



程序代码:
#include <iostream>
#include <source_location>
using namespace std;

struct foo
{
    void bar() &      { clog << source_location::current().function_name() << '\n'; }
    void bar() &&     { clog << source_location::current().function_name() << '\n'; }
};

int main( void )
{
    foo f;
    f.bar();     // 输出 void foo::bar() &
    foo().bar(); // 输出 void foo::bar() &&
}


当然,这两组还可以互相组合起来,比如 void bar() const &&
1