| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2621 人关注过本帖
标题:const修饰函数体的问题?
只看楼主 加入收藏
吉姆汤
Rank: 1
等 级:新手上路
帖 子:14
专家分:0
注 册:2020-3-10
结帖率:25%
收藏
 问题点数:0 回复次数:1 
const修饰函数体的问题?
const修饰函数体,就是在函数后面加个const,是不是只用在类对象里面?
搜索更多相关主题的帖子: const 对象 函数 
2021-09-07 08:47
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:528
帖 子:9007
专家分:53942
注 册:2011-1-18
收藏
得分:0 
只能用在 类成员函数 后面,用于修饰此成员函数,它其实限定的是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 &&
2021-09-07 10:46
快速回复:const修饰函数体的问题?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014973 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved