Featured image of post C++类和函数

C++类和函数

🇨🇳每日一言:

如果预计中的不幸没有发生的话,我们就会收获意外的喜悦。—— 人生的智慧


类简介

类是c++中面向对象编程(oop)的核心概念之一。

  • 类是用户定义的一种数据类型。要定义类,需要描述它能够表示信息和可对数据执行的哪些操作。
  • 类之于对象就像类型之于变量。
  • 类定义描述的是数据格式及其用法。
  • 对象是根据数据格式规范创建的实体。
  • 类好比所有著名演员,对象好比某个著名的演员。
1
int carrots

上面的代码将创建一个类型为int的变量(carrots) cout 是一个ostream类对象 cin是一个ostream类对象 是在iostream中定义的

  • 类描述指定了可对对象执行的所有操作。

函数

函数分为两种

有返回值的:

  • 有返回值的函数将生成一个值,这个值可赋给变量或者在其他表达式中使用:例如
1
2
double x
x = sqrt(6.25)  //调用函数sqrt()计算6.25的平方根并赋值给x。6.25为函数的参数
  • 使用函数之前,C++编译器必须知道函数的参数类型和返回值的类型。例如qurt()函数的原型是这样的:
1
double sqrt(double)
  • 在程序使用qurt()时,也必须提供原型,有两种方式
  1. 在源代码中输入函数原型。
  2. 包含头文件cmath,其中定义了原型。《推荐使用这种方式》
  • 程序示例:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// sqrt()函数的使用
#include <iostream>
#include <cmath>  //ot math.h
int main()
{
    using namespace std;
    double area;
    cout << "请输入你家正方形客厅的面积" << endl;
    cin >> area;
    double side;
    side = sqrt(area);
    cout << "您家客厅的边长是:"
         << side
         << endl;
    cout << "真大啊!" << endl;    
    return 0;
}
  • c++允许程序在任何地方声明新变量。
  • C++允许创建变量的同时进行赋值。 如:
1
double side  sqrt(area);

没有返回值的:

  • 在有些语言中,没有返回值的函数叫过程。C++中叫函数。
  • 不能将该函数调用在赋值语句或者其他表达式中。
  • 应该使用纯粹的函数调用语句:backs(1234.56)

用户自定义函数

如果库中的函数不能满足用户的需求,用户需要自定义自己的函数。通常把用户定义的函数放在main后面。 例如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
void simon(int);
int main()
{
    using namespace std;
    simon(3);  //第1次调用,参数是3
    cout <<"pick an integer"<< endl;
    int count;
    cin >> count;
    simon(count); //第2次调用,参数是count,也就是输入的数字
    cout << "done" << endl;
    return 0;
}

void simon(int n) 
{
    using namespace std;
    cout <<"simon says touch your toes " << n << " times" << endl;   //函数的作用:打印出:simon says touch your toes " n " times

}

运行结果:

1
2
3
4
5
simon says touch your toes 3 times
pick an integer
6
simon says touch your toes 6 times
done

函数格式

1
2
3
4
函数头()
{
    函数体
}

上面的函数头:void simon(int n),void标示simon()函数没有返回值

在多函数中使用using编译命令

  • 之前的函数中包含下面的编译命令:
1
using namespace std;
  • 这是函数中因为使用类cout,需要访问位于命名空间std中的cout定义
  • 我们可以将编译命令放在函数的外部,且位于函数的前面:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <iostream>
void simon(int);  //函数申明
using  namespace std;

void simon(int n )  //函数定义
{
    cout << "Simon says touch your toes " << n << " times" <<endl;
}
int main()
{
    simon(3);
    cout <<"Pick an integer:"<< endl;  
    int count;
    cin >> count;
    simon(count);
    cout << "done" << endl;
    return 0;
}
Licensed under CC BY-NC-SA 4.0
热爱生活 学无止境
使用 Hugo 构建
主题 StackJimmy 设计