c++关键字的学习,static和using

//简单语法:熟记
//1.static类型的成员变量的初始化必须在类外,比如有一个public或者private类型的static int i成员变量,初始化需要使用int class::i=1;
//2.static成员函数只能使用static类型的变量和函数,不能使用非static的成员。
//3.static类型的声明周期是整个函数结束,还有范围限制,static变量只在当前cpp文件中有效。
//4.静态变量的空间也只分配一次,前一次调用中的变量值通过下一次函数调用传递。
//  这对于在C / C ++或需要存储先前函数状态的任何其他应用程序非常有用。只会初始化一次。

``void demo() 
{ 
	// static variable 
	static int count = 0; 
	cout << count << " "; 
	
	// value is updated and 
	// will be carried to next 
	// function calls 
	count++; 
} 

int main() 
{ 
	for (int i=0; i<5; i++)	 
		demo(); 
	return 0; 
} `
输出 01234

/
//using关键字
//1.取别名,using mystr=std::string; mystr str1;取代typedef
//2.声明命名空间,using namespace std;
//3. 在 C++ 中,当派生类定义了一个与基类同名的成员函数时,
//不论参数列表如何,基类中的同名成员函数都会被隐藏。
//这意味着在派生类中无法直接调用基类中的同名成员函数,
//除非使用 using 关键字将其引入。
#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;
}
//5.改变继承的变量的访问属性
class Base{
public:
 std::size_t size() const { return n;  }
protected:
 std::size_t n;
};
class Derived : private Base {
public:
 using Base::size;
protected:
 using Base::n;
};
//类Derived私有继承了Base,对于它来说成员变量n和成员函数size都
//是私有的,
//如果使用了using语句,可以改变他们的可访问性,
//如上述例子中,size可以按public的权限访问,n可以按protected的权限访问。
//6.
#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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值