如何打印使用构造函数的对象的名称

How to print name of object that is using constructor

本文关键字:构造函数 对象 何打印 打印      更新时间:2023-10-16

我正在寻找一种从构造函数内部打印调用实例构造函数的变量名称的方法:

#include <iostream>
struct A {
    A() {
       std::cout << "variable name = " /*magic here*/ << "n";
    }
};
int main() {
    A abc;  // should output "variable name = abc"
    A def;  // should output "variable name = def"
}

这可能吗,怎么可能?

我认为

不使用宏就没有任何方法可以做到这一点。

如果你的类有一个构造函数采用 const char*,那么你可以使用一个假的构造函数宏将变量名传递给真正的构造函数。我不确定你为什么要这样做,这是一个非常丑陋的解决方案。

#define CONSTRUCT(type, name) type name(#name)