C++ using 常见用法

前言

C++ using 常见用法

Code

常规使用

#include <iostream>
// #define isNs1 1
#define isGlobal 2
using namespace std;
void func() 
{
    cout<<"::func"<<endl;
}

namespace ns1 {
    void func()
    {
        cout<<"ns1::func"<<endl; 
    }
}

namespace ns2 {
#ifdef isNs1 
    using ns1::func;    /// ns1中的函数
#elif isGlobal
    using ::func; /// 全局中的函数
#else
    void func() 
    {
        cout<<"other::func"<<endl; 
    }
#endif
}

int main() 
{
    /**
     * 这就是为什么在c++中使用了cmath而不是math.h头文件
     */
    ns2::func(); // 会根据当前环境定义宏的不同来调用不同命名空间下的func()函数
    return 0;
}

result

::func

改变访问权限

通过在类的内部使用using声明语句 , 我们可以将该类的直接或间接基类中的任何可访问成员标记出来 (只限于非私有成员) 。
using声明语句中名字的访问权限由该using声明语句之前的访问说明符来决定。

#include <iostream>

using namespace std;

class Base1 {
    public:
        Base1():value(10) {}
        virtual ~Base1() {}
        void test1() { cout << "Base test1..." << endl; }
    protected: // 保护
        int value;
};
// 默认为私有继承
class Derived1 : Base1 {
    public:
        void test2() { cout << "value is " << value << endl; }
};

/**
 * 子类对父类成员的访问权限跟如何继承没有任何关系,
 * “子类可以访问父类的public和protected成员,不可以访问父类的private成员”——这句话对任何一种继承都是成立的。
 *
 */


class Base {
public:
    Base():value(20) {}
    virtual ~Base() {}
    void test1() { cout << "Base test1..." << endl; }
// private:  //私有
    int value;
};

class Derived : Base {
public:
    using Base::value;
    void test2() { cout << "value is " << value << endl; }
};


int main() 
{
    Derived1 d1;
    d1.test2();

    Derived d;
    d.test2();
    return 0;
}

result

value is 10
value is 20

函数重载

#include <iostream>
using namespace std;

class Base{
    public:
        void f(){ cout<<"f()"<<endl;
        }
        void f(int n){
            cout<<"Base::f(int)"<<endl;
        }
};

class Derived : private Base {
    public:
        using Base::f;
        void f(int n){
            cout<<"Derived::f(int)"<<endl;
        }
};

int main()
{
    Base b;
    Derived d;
    d.f();
    d.f(1);
    return 0;
}

result

f()
Derived::f(int)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nsq_ai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值