您的位置:首页 > 编程语言 > C语言/C++

C++学习第三天

2013-04-11 17:41 295 查看
一些基础就可以略过了,看书不能太呆板。
如果把一本书看完了,剩下的就是在实际项目中进行整合,训练,然后整理成笔记。
每天敲点程序,记点笔记。

[b]变量作用域[/b]
代码:

#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

[b]判断代码输出结果[/b]
代码:

#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。

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

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: