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 world42 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 spiritis22 characters,including the newline 本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/archive/2013/04/11/3014962.html,如需转载请自行联系原作者