C++——基础变量和以及类型定义

变量类型

基础变量类型

short     //短整形,占两个字节
long      //长整型,占4个字节
int       //整形,2或4个字节
long long //长长整形,8个字节
char      //字符类型,1个字节
bool      //布尔值,1个字节,true或者false
float     //浮点数,单精度,4个字节
double    //浮点数,双精度,4个字节

有符号变量

unsigned xxx  //无符号,正值
xxx           //有符号,正负

常量

常量的定义方式有两种:

  • 方式一:
const int red_score = 50;
  • 方式二:
#define red_score = 50

自动变量

编译器根据赋给变量的初值自动推断出变量的类型。

auto index = 1;
auto rate = 500 / 0.3;

数组

一维数组

int past[5] = {
    
    1,2,3,4,5}

二维数组

int frid[2, 3] // 2行3列

多维数组

int cube[5,3,4] 

运算符

赋值运算符

grade = 96

组合运算符

自赋值加法运算符

score+= 10

递增和递减运算符

score ++;   等价于  score = score + 1;
score --;   等价于  score = score - 1;

前缀运算符和后缀运算符

//效果相同,都是将count加1
++count;
count++;

前缀运算符和后缀运算符的差别在于,后缀运算符在赋值后执行。

逻辑操作

与操作

if ((x == 5) && (y == 5))

或操作

扫描二维码关注公众号,回复: 13102828 查看本文章
if ((x == 5) || (y == 5))

非操作

if (!(grade < 70))

函数

函数的声明

int findArea(int length, int width);
  • 返回值:int
  • 函数名:findArea
  • 两个形参的名称和类型:int length, int width

具体使用方法:

#include <iostream>

//声明函数
int findArea(int length, int width);

int main()
{
    
    
    int length;
    int width;
    int area;

    std::cout << "\nWidth: ";
    std::cin >> width;
    std::cout << "\nlength: ";
    std::cin >> length;

    area = width * length;

    std::cout << "\nthe area is " << area;
    return 0;
}

//定义函数
int findArea(int l, int w)
{
    
    
    return l*w;
}

创建基本类

#include <iostream>

class Tricycle
{
    
    
    public:
        Tricycle(int initialSpeed);
        int getSpeed();
        void setSpeed(int speed);
        void pedal();
        void brake();
      
    private:
        int speed;
};

// 初始化类
Tricycle::Tricycle(int initialSpeed)
{
    
    
    setSpeed(initialSpeed);
    std::cout << "\niniting; tricycle speed: " << speed << "m/s\n";
}

// 获取当前速度
int Tricycle::getSpeed()
{
    
    
    return speed;
}

// 设置速度
void Tricycle::setSpeed(int newSpeed)
{
    
    
    if(newSpeed >= 0)
    {
    
    
        speed = newSpeed;
    } 
}

// 踩踏板
void Tricycle::pedal()
{
    
    
    setSpeed(speed + 1);
    std::cout << "\nPedaling; tricycle speed: " << speed << "m/s\n";
}

void Tricycle::brake()
{
    
    
    setSpeed(speed - 1);
    std::cout << "\nBraking; tricycle speed: " << speed << "m/s\n";
}

int main()
{
    
    
    Tricycle myBike(0);
    myBike.setSpeed(0);
    myBike.pedal();
    myBike.pedal();
    myBike.brake();
    myBike.brake();
    myBike.brake();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45779334/article/details/114664666
今日推荐