![](/img/trans.png)
[英]Question about npos and -1 for the output of a C++ function
[英]quick question about static function in c++
C ++中的静态函数
因此,此类只能有一个静态函数实例。 对?
在C ++中,静态成员函数就像普通的全局函数一样,只是名称的可见性不同:
this
指针,因此它只能访问您已授予其访问权限的对象的那些部分(例如,作为参数传递)。 extern "C"
。 将函数设为静态允许调用它而无需实例化其所属类的实例。 learncpp.com上有更多有关此主题的内容,请查看以下示例,该示例将无法编译:
class Foo
{
public:
static void Bar1();
void Bar2();
};
int main(int argc, char* argv[])
{
Foo::Bar1();
Foo x;
x.Bar2();
Foo::Bar2(); // <-- error C2352: 'Foo::Bar2' : illegal call of non-static member function
return 0;
}
静态成员函数(在类内部)意味着您可以调用该函数而无需先创建类的实例。 这也意味着该函数无法访问任何非静态数据成员(因为没有实例可以从中获取数据)。 例如
class TestClass
{
public:
TestClass() {memberX_ = 10;}
~TestClass();
// This function can use staticX_ but not memberX_
static void staticFunction();
// This function can use both staticX_ and memberX_
void memberFunction();
private:
int memberX_;
static int staticX_;
};
无需实际创建该类型的变量即可调用静态函数,例如:
class Foo
{
public:
static void Bar();
void SNAFU();
};
int main( void )
{
Foo::Bar(); /* Not necessary to create an instance of Foo in order to use Bar. */
Foo x;
x.SNAFU(); /* Necessary to create an instance of Foo in order to use SNAFU. */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.