C++调用静态方法

C++ calling a static method

假设您有以下 class:

struct Foo {        
    static void print(std::string x) { std::cout << x << std::endl; }       
};

调用print和调用

有什么区别
Foo foo; //Or a pointer...
foo.print("Hello world");

Foo::print("Hello world");

?

调用点没有区别。一打六打。

Foo::print("Hello world");地道;已经形成了一种约定,它向 reader 发出信号,表明 print 可能 是一个 static 函数。为此,在您的特定情况下使用 foo.print("Hello world"); 是特殊的,因此令人困惑。因此,请避免这种方式,特别是如果引入不必要的实例会产生开销 foo.

请注意,如果您想在复杂的 class 层次结构中的另一个方法中实现对 print 的特定覆盖,也可以使用使用范围解析运算符的表示法!因此我在上面使用 likely

第一个版本必须构造和销毁一个 Foo

然后有一个明显的相似之处,即两个版本在执行函数调用时做同样的事情(构造字符串、打印等)。

不太明显的区别在于两个表达式的计算。你看,即使调用不需要 foo,它仍然作为表达式的一部分进行计算:

[class.static]/1

A static member s of class X may be referred to using the qualified-id expression X​::​s; it is not necessary to use the class member access syntax to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object expression is evaluated.

在你的情况下这没有任何意义。但在某些情况下,它可能会阻止您的程序进行编译。 .

你的例子没有区别。请记住,静态变量在 class 的所有实例之间共享。因此,您可以通过范围运算符或通过成员选择来访问它们:

class A{
    public:
        A(){count++;}
        ~A(){count--;}

        static int count;
};

int A::count = 0;

int main(){
    A aObj, bObj, cObj;

    std::cout << "number of A instances: " << A::count << std::endl;
    std::cout << "number of A instances: " << aObj.count << std::endl;

    return 0;
}