'static' can indeed be used in C++ to create a Static Member Function

本文介绍了如何在C++中正确地定义和使用静态成员函数。通过一个矩形相交判断的例子,展示了静态成员函数的声明与定义的区别,并给出了完整的代码实现。
'static' can indeed be used in C++ to do what you want - to create a Static Member Function.
The compiler message is actually telling you that the 'static' keyword is not valid on the definition of the method, it should only be used in the class definition.
So the following compiles
class Rect
{
private:
    
int x;
    
int y;
    
int width;
    
int height;
public:
    
static bool intersects(Rect& a, Rect& b);  //Use 'static' in declaration
};

bool Rect::intersects(Rect& a, Rect& b)    //no 'static' - compiler know that from class declaration
{
    
return !(a.x > b.x+(b.width-1|| a.x+(a.width-1< b.x || a.y > b.y+(b.height-1|| a.y+(a.height-1< b.y);
}

int main()
{
    Rect myRect1,myRect2;
    
bool theSame;
    theSame 
= Rect::intersects(myRect1,myRect2);
    
return 0;
};

I have changed the result type to bool, as that appears to be your intent.
I'll leave it to one of the experts to explain why static should only appear in the declaration - I sometimes feel the real reason for things like that are to make life harder for people new to the language:-)

转载于:https://www.cnblogs.com/smartvessel/archive/2011/05/05/2037729.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值