nob*_*alG 7 c++ operator-overloading
我正在学习在一个非常简单的程序中重载"<<",在我的学习期间,我发现了以下令人惊讶的程序输出.
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
class student
{
int age;
public:
student(){}
student(int a){age=a;}
friend ostream &operator<<(ostream &stream,student o);
};
/*operator overloaded in this block*/
ostream &operator<<(ostream &stream,student o)
{
stream<<o.age;
return stream;
}
int main()
{
student ob1(20),ob2(020);
cout<<ob1; /*will yield 20(as desired)*/
cout<<"\n"<<ob2; /*yielding 16(why so)*/
_getch();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
任何解释请
pmr*_*pmr 11
0是C++整数文字的八进制前缀,八进制中的20是十进制的16.
进一步解释:如果文字以0开头,则数字的其余部分将被解释为八进制表示.在你的例子中2*8 ^ 1 + 0*8 ^ 0.
整数文字的语法在最新标准草案的§2.14.2中给出.
student ob1(20),ob2(020);
Run Code Online (Sandbox Code Playgroud)
您已写入020,其中C和C++被解释为八进制数(基数为8),因为开始时为零.所以020的十进制值为16.
| 归档时间: |
|
| 查看次数: |
583 次 |
| 最近记录: |