阿鑫来了  

命名空间 :

变量 , 函数和类的名称若都存在于全局作用域中 , 可能会导致很多冲突 , 使用命名空间

的目的是对标识符的名称进行本地化 , 以免命名冲突或名字污染 , namespace关键字

的出现就是针对这一问题 .

namespace + 命名空间名称  { 变量 , 函数 }

#include<stdio.h>
#include<stdlib.h>
//命名空间N1下的变量和函数
namespace N1{
    int a=10;
    void fun1(){
        printf("N1: fun1()\n");
    }

    //嵌套
    namespace N2{
        int b=15 ;
        void fun1(){
            printf("N1:N2: fun1()\n");
        }
    }
}

//分段
namespace N1{
    //int a;重定义
    int b=20;
    void fun2(){
        printf("N1: fun2()\n");
    }
}


//全局作用域下的变量和函数
int a = 5;
void fun1(){
    printf("fun1()\n");
}

void test(){
    //全局 : a
    printf("a: %d\n", a);
    //命名空间中的成员访问形式
    //1.命名空间 + :: + 成员
    printf("N1::a: %d\n", N1::a);
    //2.using 命名空间::成员
        using N1::b;
        printf("N1::b: %d\n", b);
 }

int main(){
    test();
    system("pause");
    return 0;
}

 

C++中的输入输出 :

#include<stdio.h>
#include<stdlib.h>
#include<iostream>

//使用这个就不用使用 std::
using namespace std;
void test(){
        //C++头文件中定义所有成员都属于std命名空间
        int a, b, c;
        //cin : 支持连续输入,也是从左向右
        std::cin >> a >> b >> c;
        //endl换行
        std::cout << endl;
        //cout : 支持连续输出,从左向右
        std::cout << a << " " << b << " " << c << endl;
}

int main(){
    test();
    system("pause");
    return 0;
}

 

定义函数 :

#include<stdio.h>
#include<stdlib.h>
#include<iostream>

using namespace std;

void fun1(int a){
    cout << a << endl;
}

//定义函数时给定一个默认值
void fun2(int a = 10){
    cout << a << endl;
}

//全缺省 : 所有参数都有默认值
void fun3(int a=10,int b=20,int c=30){
    cout << a << " " << b << " " << c << endl;
}

int a;
//半缺省 : 部分参数有默认值
void fun4(int a, int b = 1, int c = 2){
    cout <<a<< " " << b << " " << c << endl;
}
//两种错误写法 , 半缺省 , 必须从右往左连续赋值 , 中间不能有间隔
//void fun4(int a=1, int b , int c = 2){}
//void fun4(int a=1, int b = 2, int ){}

void test(){
    fun1(20);/*必须要传值*/
    fun2();/*可以不传值,有默认值10*/
    fun3();
}

int main(){
    test();
    system("pause");
    return 0;
}

 

函数重载 :

同一个作用域下函数名相同,参数不同
                                            参数不同:参数个数,顺序,类型

返回值类型不能当做函数重载的依据.

#include<stdio.h>
#include<stdlib.h>
#include<iostream>

using namespace std;
//函数重载:
//函数名相同,参数不同
//           参数不同:参数个数,顺序,类型

void fun(char a, int b){
    cout <<"fun(char,int)"<< endl;
}

//参数顺序不同
void fun(int b, char a){
    cout << "fun(int,char)" << endl;
}

//参数个数不同
void fun(char a, int b, double c){
    cout << "fun(char,int,double)" << endl;
}

void test(){
    int a=1;
    char b = 'a';
    double c = 1.0;
    fun(b, a);
    fun(a, b);
    fun(b, a, c);
}

int main(){
    test();
    system("pause");
    return 0;
}

 

在C++中按照C语言的规则编译
在前面加上 extern "C"

extern "C"{
    int add(int a, int b);
}

 

posted on 2021-04-19 22:33  阿鑫来了  阅读(70)  评论(0)    收藏  举报