C++语言基础 例程 C++的数据类型和运算符

贺老师的教学链接

第一个C++程序

#include <iostream>       //包含头文件iostream
using namespace std;      //使用命名空间std
int main( )
{
      cout<<"Hello World."<<endl;    //输出结果
      return 0;
}

结构体类型在定义变量时,其前struct可以省略

#include <iostream>
using namespace std;
struct student
{
    int no;
    float math;
};
int main( )
{
    int n;
    cin>>n;
    student wang;  //C语言中,必须struct student wang
    wang.no=n;
    cin>>wang.math;
    cout<<wang.no<<"  "<<wang.math<<endl;
    return 0;
}

新增作用域运算符 ::

#include <iostream>   
using namespace std;
float a=2.4;           // 全局变量a
int main()
{
     int a=8;              // 局部变量a
     cout<<a<<endl;  // a为局部变量
     cout<<::a<<endl;  // ::a表示全局变量a
} 

std::,表明使用命名空间std中定义的标识符

#include <iostream>   
//这儿不写使用的命名空间
float a=2.4;          
int main()
{
     int a=8;              
     std::cout<<a<<std::endl;  
     std::cout<<::a<<std::endl;  
} 

引用的简单使用

#include <iostream>
#include <iomanip>
using namespace std;
int main( )
{
      int a=10;
      int &b=a;  //声明引用类型变量要同时初始化 
      a=a*a; 
      cout<<a<<"  "<<b<<endl; 
      b=b/5;  
      cout<<b<<"  "<<a<<endl;
      return 0;
}

增加引用类型,主要用于扩充函数传递数据功能

#include <iostream>
using namespace std;
void swap(int &a,int &b);
int main( )
{
    int i,j;
    i=3,j=5;
    swap(i,j);
    cout<<"i="<<i<<"  "<<"j="<<j<<endl;
    return 0;
}

void swap(int &a,int &b)
{
    int temp;
    temp=a;
    a=b;
    b=temp;
}

常变量(constant variable)

#include<iostream>
using namespace std;
const int price = 30; 
int main ( )
{
    int num, total;
    num=10;
    total=num * price;
    cout<<"total="<<total<<endl;
    return 0;
}

符号常量(宏定义) vs.常变量

#include <iostream>
using namespace std;
#define PRICE 30  //不是语句,末尾不加分号
int main ( )
{
    int num, total;
    num=10;
    total=num * PRICE;
    cout<<"total="<<total<<endl;
    return 0;
}

C++的程序员更爱常变量

#include<iostream>
using namespace std;
const int price = 30; 
int main ( )
{
    int num, total;
    num=10;
    total=num * price;
    cout<<"total="<<total<<endl;
    return 0;
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迂者-贺利坚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值