c++ - C++中的静态函数
问题描述
我在学习 C++ 时提出了一个问题。这是关于静态功能的。在这个头文件中,我创建了一个静态函数。
using namespace std;
class Date
{
public:
int dd, mm, yy;
public:
//Date();
Date(int d, int m, int y);
static bool LeapYear(Date t);
};
在这个源文件中,我定义了函数
{
if ((t.yy % 400 == 0) || (t.yy % 4 == 0) && (t.yy % 100 != 0))
return true;
else
return false;
}
据说静态函数无法访问非静态成员。但是当我将一个对象放入该函数时,它仍然可以工作。谁能为我解释一下?谢谢!
解决方案
静态和非静态成员函数之间的区别在于,当您调用非静态成员函数时,指向类实例的指针会作为第一个参数(this指针)隐式传递。您需要一个类(对象)的实例来调用非静态成员函数。因此,成员函数被授予访问类实例成员的权限。
相反,静态成员和静态成员函数不属于类实例,它们只是类定义的一部分。这就是为什么他们不能访问任何非静态类成员。这也是静态函数不能标记为 const 的原因,因为没有实例可以修改。
class Date
{
public:
int dd, mm, yy;
public:
Date(int d, int m, int y);
// static function
// can't be marked const because it makes no sense
static bool LeapYear(Date t) /*const*/ {
if ((t.yy % 400 == 0) || (t.yy % 4 == 0) && (t.yy % 100 != 0))
return true;
else
return false;
}
// member function - has access to this and thus to any non-static member of the instance
// marked const because it doesn't change the instance
bool isLeap() const {
if ((/*this->*/yy % 400 == 0) || (yy % 4 == 0) && (yy % 100 != 0))
return true;
else
return false;
}
};
推荐阅读
- python - mako 访问代码块外的变量
- html - HTML:在输入字段中显示键
- sql - SQL选择排序组合列
- swift - 如果“UITextField”中的文本有效,如何创建“RxAction”以启用/禁用按钮?
- r - 在 sf 对象上设置正确的 crs 以绘制坐标点
- java - 如何将我的二维数组填充为相同的值
- c# - 使用 Where 子句在列表中搜索列表
- amazon-web-services - AWS 上的 Kubernetes 集群使用没有互联网出口的 kops
- javascript - Javascript获取具有特定类的所有祖先
- javascript - 在 React 中显示图像,有一些问题