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;
}
答
要区分入栈顺序和输出顺序。
输出顺序从左向右,所以先输出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;