简体   繁体   English

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

[英]How to print name of object that is using constructor

I am looking for a way to print the name of the variable on which an instance's constructor is being invoked, from inside the constructor: 我正在寻找一种从构造函数内部打印在其上调用实例的构造函数的变量名称的方法:

#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"
}

Is this possible and how? 这有可能吗?

I don't think there's any way to do that without using macros. 我认为不使用宏就没有任何方法可以做到这一点。

If your class had a constructor taking a const char* then you could use a fake constructor macro to pass the variable name into the real constructor. 如果您的类的构造函数使用const char *,则可以使用伪造的构造函数宏将变量名传递给实际的构造函数。 I'm not sure why you'd want to do that though and this is a pretty ugly solution. 我不确定为什么要这么做,但这是一个非常丑陋的解决方案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用名称创建参数化构造函数对象 - Parameterized Constructor Object creation using name 实例化 object 并使用 c++ 宏将其名称传递给构造函数 - Instantiate object and pass its name to constructor using c++ macro 是否可以打印对象的名称? - Is it possible to print the name of an object? 在构造函数中使用对象 - Using object inside constructor 有什么方法可以在参数化构造函数中输入 10 个学生的详细信息,并在 C++ 中使用带有对象数组的成员函数打印它 - Is there any way to enter 10 students detail in parameterized constructor and print it using member function with array of object in c++ 如何在 class 成员 function c++ 中打印 object 名称? - How to print object name in class member function c++? 我需要复制构造函数吗? 以及如何使用复制构造函数将const对象复制到非const对象 - do i need copy constructor ? and how copy const object to non const object using copy constructor 如何在构造函数中为具有同名成员的 Object 限定类型名称? - How do you Qualify a Type Name in a Constructor for an Object which has a Member of the Same Name? 在构造函数中使用类成员名称 - Using class member name in a constructor 如何在C ++中使用构造函数将值重新分配给对象 - how to reassign value to an object using constructor in c++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM