C++学习第三天

一些基础就可以略过了,看书不能太呆板。
如果把一本书看完了,剩下的就是在实际项目中进行整合,训练,然后整理成笔记。
每天敲点程序,记点笔记。
 
变量作用域
代码:

#include <iostream>
#include <string>
#include <conio.h>
std::string s1 = "hello";  //全局
int main(){
    std::string s2 = "world"; //局部
    std::cout<<s1<<" "<<s2<<std::endl;
    int s1 = 42;  //局部+隐式全局
    std::cout<<s1<<" "<<s2<<std::endl;
    getch();
    return 0;
}


结果:
hello world
42 world

判断代码输出结果
代码:

#include <iostream>
#include <string>
#include <conio.h>
int i = 42;
int main(){
    int i = 100,sum = 0;
    for(int i = 0;i!=10;++i)
            sum += i;
    std::cout<<i<<" "<<sum<<std::endl;
    getch();
    return 0;
}

结果:
100 45

用class和struct关键字定义类的唯一差别在于默认访问级别:默认情况下,struct的成员为public,而class的成员为private。

一旦使用了using声明,我们就可以直接引用名字,而不需要再引用改名字的命名空间了。
代码:

#include <iostream>
#include <string>
#include <conio.h>
using std::cin;
using std::string;
using std::cout;
int main(){
    string s;
    cin>>s;
    cout<<s;
    getch();
    return 0;
}

#include <iostream>
#include <string>
#include <conio.h>
using std::cin;
using std::string;
using std::cout;
using std::endl;
int main(){
    string st("The expense of spirit\n");
    cout<<"The size of "<<st<<"is"<<st.size()
               <<" characters,including the newline"<<endl;
    getch();
    return 0;
}

结果:
The size of The expense of spirit
is22 characters,including the newline

原文地址:https://www.cnblogs.com/jiqing9006/p/3014962.html