C到C++的快速教程02

1.头文件:

C++头文件不是以.h结尾,C语言中的标准库文件如math,h,stdio.h在C++中被命名为cmath,cstdio                  

2.命名空间:

为防止名字冲突(出现同名),C++引入名字空间(namespace)。通过::运算符限定某个名字属于哪个名字空间。

namespace name
{
     //变量,函数,类等
}
//电子::“小明”

 通常有三种方法使用名字空间X的名字name:

/*
using namespace X;//引入整个名字空间
using X::name;//使用单个名字
X::name;//程序中加上名字空间前缀,如X::
*/
#include <cstdio> 
namespace first
{
   int a;
   void f(){/*...*/}
   int g(){/*...*/}
}

namespace second
{
   double a;
   double f(){/*...*/}
   char g;
}

int main ()
{
   first::a = 2;
   second::a = 6.453;
   first::a = first::g()+second::f();
   second::a = first::g()+6.453;

   printf("%d
",first::a);
   printf("%lf
",second::a);

   return 0;
}
View Code
 1 #include<iostream>
 2 //命名空间的using声明
 3 //using namespace::name;
 4 using std::cin;  
 5 int main()
 6 {
 7     int i;
 8     cin >> i;
 9     cout << i;//错误,没有对应的using声明
10     std::cout << i;
11     return 0;
12 }
View Code

3.C++的输入和输出

#include <iostream> //标准输入输出头文件 
#include <cmath> 
using namespace std; //引入整个名字空间std中的所有名字 
                     //cout cin都属于名字空间std;       
//cout输出用<<运算符  cin紧跟>>运算符      
int main() {
    double a;
    cout << "从键盘输入一个数" << endl;
    cin >> a;
    a = sin(a);
    cout << a;
    return 0;
}

4.程序块{}内部作用域可定义域外部作用域同名的变量,在该块里就隐藏了外部变量

#include <iostream> 
using namespace std;

int main ()
{
   double a;

   cout << "Type a number: ";
   cin >> a;

   {
      int a = 1; // "int a"隐藏了外部作用域的“double a"       
      a = a * 10 + 4;
      cout << "Local number: " << a << endl;
   }

   cout << "You typed: " << a << endl; //main作用域的“double a" 
   return 0;
}
View Code

5.struct的加强

struct Student
{
   char name[20];
   int age;
 
};

//C语言:在定义变量结构体变量时一定要在前面加上struct关键字
struct Student stu={"wang",10};
//C++:可以直接用结构体名来定义变量
Student stu ={"wang",10};

 6..访问和内部作用域变量同名的全局变量,要用全局作用域限定 ::

#include <iostream> 
using namespace std;

double a = 128;

int main (){
   double a = 256;

   cout << "Local a: " << a << endl;
   cout << "Global a: " <<::a << endl;  //::是全局作用域限定    

   return 0; 
}

7.  内联函数

  对于不包含循环的简单函数,建议用inline关键字声明 "inline内联函数"编译器将内联函数调用用其代码展开,称为“内联展开”,避免函数调用开销, 提高程序执行效率

  内联函数没有普通函数调用时的额外开销(如压榨、跳转、返回)

inline int myMax(int a, int b)
{
     return (a>b?a:b);

}
原文地址:https://www.cnblogs.com/wy9264/p/10604060.html