c++学习day01基础知识学习

一、代码示例解析:

1 #include <iostream>
2 int main()
3 {
4     using namespace std;
5     cout << "come up and C++ me some time.";
6     cout << endl;
7     cout << "you are right!"<<endl;
8     return 0;
9 }

运行结果:

come up and C++ me some time.
you are right!

说明:这里的using namespace std 为名称空间,它是为了让编写大型程序以及将多个厂商现有的代码组合在一起,也是为了统一管理。但是如果我们不使用名称空间的话,上面代码一般是这样的:

#include <iostream>
int main()
{
    //using namespace std;
    std :: cout<<"come up and C++ me some time.";
    std ::cout << std::endl;
    std ::cout << "you are right!"<<std::endl;
    return 0;
}

运行结果和第一个示例是一样的,一般在做大型项目的时候会采用这种写代码风格,平时我们学习用的比较多是使用using 编译指令,也就可以使用名称空间里面已经定义好的名称了,就不用这样写代码了,就是第一个示例,这种代码风格有点偷懒,不建议这种写法。cout <<"you are right !"  ,其中“<< ”表示把这个字符串发送给cout ;endl 是一个控制符,它表示换行的意思,和换行符“\n”的作用类型,而且他也位于头文件iostream中,

注意:刚才上面的“<<”表示插入运算符,这个有点和按位左移运算符一样,但是他们的作用不同,这个就是运算符重载的概念,就是一个运输符,通过重载,将含有不同的功能描述。

接下来我们再来看一个实例:

#include <iostream>
int main()
{
    using namespace std;
    int carrots;
    
    cout << "how  many carrots do you have ?"<< endl;
    cin >> carrots;
    cout<< "here you are two more.";
    carrots=carrots + 2;
    cout << "now you have "<<carrots<<" carrots."<<endl;
    return 0;
}

运行结果:

how  many carrots do you have ?
4
here you are two more.now you have 6 carrots.

说明:这里我们主要来学习一下cin的使用方法,cin >>carrots,这条语句主要是把我们要输入的值赋给carrots变量,

猜你喜欢

转载自www.cnblogs.com/1121518wo/p/11077004.html