Something about static Methods in C++ you should know

本文探讨了C++中静态方法的特点与限制,包括不能声明为const或虚拟方法,以及在子类中重名静态方法的行为表现。通过示例代码展示了不同调用方式下静态方法的表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.
It's not allowed to declare static methods as const.
The non-static versions of  the methods can be marked as const.


2.
The static methods are scoped by the name of the class in which they are defined, but are not methods that apply to a specific object.

In C++, you cannot override a static method.

First of all, a method cannot be both static and virtual. 

If you have a static method in your subclass with the same name as a static method in your superclass, you actually have two separate methods.  These two methods are in no way related.

class SuperStatic
{
public:
    static void beStatic() 
    {
        cout << "SuperStatic being static." << endl; 
    }
};

class SubStatic : public SuperStatic
{
public:
    static void beStatic() 
    {
        cout << "SubStatic keepin' it static." << endl; 
    }
};

SuperStatic::beStatic();
SubStatic::beStatic();

The results:

SuperStatic being static.
SubStatic keepin' it static.

SubStatic mySubStatic;
SuperStatic& ref = mySubStatic;
mySubStatic.beStatic();
ref.beStatic();

The results:
SubStatic keepin' it static.
SuperStatic being static.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值