三十畫生 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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog