三十畫生 2019-07-16 18:28 采纳率: 50%
浏览 591
已采纳

C++中关于常成员函数的调用按什么顺序?

程序的输出为
with no const
with const
12
16
请问为什么不是字符串和数字一组一组输出,而且不先调用常成员函数?

程序如下:
#include
using namespace std;
class A
{
private:
int w,h;
public:
int getValue() const;
int getValue();
A(int x,int y)
{
w=x;h=y;
}
A(){}
};
int A::getValue()
{
cout<<"with no const"<<endl;
return w*h;
}
int A::getValue() const
{
cout<<"with const"<<endl;
return w*h;
}
int main()
{
A const a(3,4);
A c(2,8);
cout<<a.getValue()<<endl<<c.getValue()<<endl;
}

  • 写回答

1条回答 默认 最新

  • D_DreKing 2019-07-17 08:55
    关注

    要区分入栈顺序和输出顺序。
    输出顺序从左向右,所以先输出12在输出16。
    入栈顺序从右往左,先执行c.getValue(),在执行a.getValue() const。所以先输出with no const
    这就是一个规则。不光cout,C语言里print也这样。
    你可以测试一下
    int a = 0 ;
    cout << a++ << a++ << endl ;
    或者printf("%d %d", a++, a++) ;
    会输出1,0;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵