C++使用非静态函数重载静态函数

Ala*_*ing 36 c++ static overloading non-static

我想打印两个不同的东西,这取决于一个函数是静态调用Foo::print()还是来自一个实例Foo foo; foo.print();

编辑:这是一个绝对不起作用的类定义,已经有几个人回答了.

class Foo {
    string bla;
    Foo() { bla = "nonstatic"; }

    void print() { cout << bla << endl; }
    static void print() { cout << "static" << endl; }
};
Run Code Online (Sandbox Code Playgroud)

但是,有没有一种很好的方法来实现这种效果?基本上,我想做:

if(this is a static call)
    do one thing
else
    do another thing
Run Code Online (Sandbox Code Playgroud)

换句话说,我知道PHP可以检查是否*this定义了变量,以确定是否静态调用该函数.C++是否具有相同的功能?

In *_*ico 57

不,标准直接禁止:

ISO 14882:2003 C++标准13.1/2 - 可重载声明

某些函数声明不能​​重载:

  • 仅在返回类型上不同的函数声明不能​​重载.
  • 如果它们中的任何一个是static成员函数声明(9.4),则不能重载具有相同名称和相同参数类型的成员函数声明.

...

[例:

class X {
    static void f();
    void f();                // ill-formed
    void f() const;          // ill-formed
    void f() const volatile; // ill-formed
    void g();
    void g() const;          // OK: no static g
    void g() const volatile; // OK: no static g
};
Run Code Online (Sandbox Code Playgroud)

- 末端的例子]

...

此外,无论如何它都是模棱两可的,因为它可以在实例上调用静态函数:

ISO 14882:2003 C++标准9.4/2 - 静态成员

可以使用qualified-id 表达式引用s类的静态成员; 没有必要使用类成员访问语法(5.2.5)来引用a .甲 构件可被称为使用类的成员访问语法,在这种情况下被评估.[例:XX::sstatic memberstaticobject-expression

class process {
public:
        static void reschedule();
}
process& g();
void f()
{
        process::reschedule(); // OK: no object necessary
        g().reschedule();      // g() is called
}
Run Code Online (Sandbox Code Playgroud)

- 末端的例子]

...

因此,你所拥有的东西会含糊不清:

class Foo
{
public:
    string bla;
    Foo() { bla = "nonstatic"; }
    void print() { cout << bla << endl; }
    static void print() { cout << "static" << endl; }
};

int main()
{
    Foo f;
    // Call the static or non-static member function?
    // C++ standard 9.4/2 says that static member
    // functions are callable via this syntax. But
    // since there's also a non-static function named
    // "print()", it is ambiguous.
    f.print();
}
Run Code Online (Sandbox Code Playgroud)

为了解决您是否可以检查调用成员函数的实例的问题,有this关键字.的this关键字指向的对象为其调用功能.但是,this关键字将始终指向一个对象,即它永远不会NULL.因此,无法检查函数是静态调用还是不是PHP调用.

ISO 14882:2003 C++标准9.3.2/1 - 这个指针

在非静态(9.3)成员函数的主体中,关键字this是非左值表达式,其值是调用该函数的对象的地址.