gpt4 book ai didi

c++ - 有什么方法可以确定上下文是否允许使用 "this"?

转载 作者:太空狗 更新时间:2023-10-29 21:25:17 25 4
gpt4 key购买 nike

有什么方法可以确定上下文是否允许使用“this”?

我的目标是编写一个通用宏,用于日志记录,根据上下文使用“this”(例如,打印“this”的值)。

最佳答案

即使你能做到这一点,你也永远无法使用它。代码必须是合法的,即使它永远不会被调用,并且在这样的上下文中提及 this 是不合法的。考虑:

if (this_is_legal())
std::cout << this << std::endl;
else
std::cout << "not in member function" << std::endl;

好吧,即使神奇的 this_is_legal 起作用,这段代码也不会编译。因为第一个 std::cout 行不会在 this 不合法的上下文中编译。

你可以做一个非常丑陋的 const void *getThis() { return NULL; } 作为全局函数和 const void *getThis() { return this; } 作为成员函数。这将为您提供一个返回 NULLthis 的函数。依赖于未定义的行为,您必须希望 this 指针在没有成员变量的基类中不会被修改。

关于c++ - 有什么方法可以确定上下文是否允许使用 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14287752/

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