gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:08 25 4
gpt4 key购买 nike

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

编辑:这是一个绝对不起作用的类定义,正如一些人已经回答的那样。

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

void print() { cout << bla << endl; }
static void print() { cout << "static" << endl; }
};

但是,有没有什么好的方法可以达到这个效果呢?基本上,我想做的是:

if(this is a static call)
do one thing
else
do another thing

换句话说,我知道 PHP 可以检查 *this 变量是否被定义,以确定函数是否被静态调用。 C++ 有同样的能力吗?

最佳答案

不是,是标准直接禁止的:

ISO 14882:2003 C++ Standard 13.1/2 – Overloadable declarations

Certain function declarations cannot be overloaded:

  • Function declarations that differ only in the return type cannot be overloaded.
  • Member function declarations with the same name and the same parameter types cannot be overloaded if any of them is a static member function declaration (9.4).

...

[Example:

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
};

—end example]

...

此外,无论如何它都会有歧义,因为可以在实例上调用静态函数:

ISO 14882:2003 C++ Standard 9.4/2 – Static members

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 (5.2.5) 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. [Example:

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

—end example]

...

所以你所拥有的东西会有歧义:

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++ Standard 9.3.2/1 – The this pointer

In the body of a nonstatic (9.3) member function, the keyword this is a non-lvalue expression whose value is the address of the object for which the function is called.

关于C++ 用非静态函数重载静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49457872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com