1 C++统一初始化:
初始化列表 解决方案
int main()
{
int a=10;
int b(10);
int c{10};
int ar[10]={1,2,3,4,5,6,7,8,9,10};
int br[10]{1,2,3,4,5,6,7,8,9,10};
return 0;
}
2 输入输出
#include<stdio.h>
int main()
{
int a=0;
char ch='0';
scanf("a=%d ch=%c \n",a,c);
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a=0;
char ch='0';
cin>>a>>ch;
cout<<"a = "<<a<<"ch = "<<ch<<endl;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
const int n=128;
char str[n];
cin>str;
cout<<str<<endl;
cin.getline(str,n);
cout<<str<<end;
cin.getline(str,n,'#');
cout<<str<<endl;
return 0;
}
总结: ??使用cout标准输出(控制台)和cin标准输入(键盘)时,必须包含 < iostream > 头文件以及std标准命名空间。endl 相当于 ’ n’;
3 const 与指针
C语言中以变量为主
int main()
{
const int n = 10;
int ar[n] ={1,2};
int *p =(int*) &n;
*p = 100;
printf("%n = %d *p = %d n",n,*p);
return 0;
}
C++ 中以常量为主
int main()
{
const int n = 10;
int ar[n] = {1,2,3,4};
int *p = (int *)&n;
*p = 100;
cout<<"n = "<<n<<" *p = "<<*p<<endl;
return 0;
}
int main()
{
int a = 10, b = 10;
int *p1 = &a;
const int *p2 = &a;
int const *p2 = &a;
int * const p3 = &a;
const int * const p4 = &a;
}
int main()
{
int a = 0;
int *p1 = &a;
const int *p2 = &a;
int * const p3 = &a;
const int * const p4 = &a;
return 0;
}
常变量与指针
int main()
{
const int a = 10;
int *p1 =&a;
const int *p2 = &a;
int * const p3 = &a;
const int * const *p4 = &a;
int *p5 = (int*) &a;
return 0;
}
同类型指针的赋值兼容规程
int main()
{
int a = 10,b = 20;
int *p = &a;
int *s1 = p;
const int *s2 = p;
int * const s3 = p;
const int * const s4 = p;
}
总结:能力强的指针赋值给能力收缩的指针 练习1
int main()
{
int a = 10, b = 20;
const int *p = &a;
int *s1 = p;
const int *s2 = p;
int * const s3 = p;
const int * const s4 = p;
}
练习2
int main()
{
int a = 10, b = 20;
int * const p = &a;
int *s1 = p;
const int *s2 = p;
int * const s3 = p;
const int * const s4 = p;
}
|