不,是标准直接禁止的:
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
};
——结束示例]
...
此外,无论如何它都是模棱两可的,因为可以在实例上调用静态函数:
ISO 14882:2003 C++ 标准 9.4/2 – 静态成员
可以使用qualified-id
表达式来引用s
类的静态成员;不必使用类成员访问语法 (5.2.5) 来引用. 可以使用类
成员访问语法来引用成员,在这种情况下会评估。[例子:X
X::s
static member
static
object-expression
class process {
public:
static void reschedule();
}
process& g();
void f()
{
process::reschedule(); // OK: no object necessary
g().reschedule(); // g() is called
}
——结束示例]
...
所以你所拥有的会有歧义:
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();
}
为了解决您是否可以检查正在调用成员函数的实例的问题,有this
关键字。this
关键字指向调用函数的对象。但是,this
关键字将始终指向一个对象,即它永远不会是NULL
. 因此,不可能检查一个函数是否被静态调用,就像 PHP 一样。
ISO 14882:2003 C++ 标准 9.3.2/1 – this 指针
在非静态 (9.3) 成员函数的主体中,关键字this
是一个非左值表达式,其值是调用该函数的对象的地址。