c++ - 重载插入器和奇怪的输出(对于 '20' 和 '020')

标签 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;
 }

请解释一下

最佳答案

0 是 C++ 整数文字的八进制前缀,八进制的 20 是十进制的 16。

进一步解释:如果文字以 0 开头,则其余数字将被解释为八进制表示形式。在您的示例中,2*8^1 + 0 * 8^0。

整数文字的语法在最新标准草案的 §2.14.2 中给出。

关于c++ - 重载插入器和奇怪的输出(对于 '20' 和 '020'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7027025/

相关文章:

C++ 函数原型(prototype)

c++ - 使用模板重载运算符,但防止重新定义

c++ - 如何重载下标运算符以允许角色扮演角色数组?

c++ - 模板 C++ 一次重载多个运算符

c++ - 指向指针或引用的迭代器 - 错误

c++ - 具有前向声明类的模板函数

c++ - 在 C++ 中使用树计算 Postfix 表达式

c++ - 奇怪的功能查找

c++ - 继承运算符 +()

c++ - C++ 指针的问题