如何打印使用构造函数的对象的名称
How to print name of object that is using 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"
}
这可能吗,怎么可能?
我认为
不使用宏就没有任何方法可以做到这一点。
如果你的类有一个构造函数采用 const char*,那么你可以使用一个假的构造函数宏将变量名传递给真正的构造函数。我不确定你为什么要这样做,这是一个非常丑陋的解决方案。
#define CONSTRUCT(type, name) type name(#name)
相关文章:
- 对象实例化调用构造函数的次数太多
- Arduino C++在构造函数中用参数声明对象数组
- 模板,函数使用错误的构造函数来复制我的对象
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 通过构造函数创建的所有对象都具有相同的向量
- 是什么让放置新调用对象的构造函数?
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- C++ 对象指针数组的复制构造函数
- 在构造函数中输入对象时C++类成员作用域
- C++:将初始化的对象传递给另一个类的构造函数;需要不必要的构造函数吗?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 如何从构造函数副本 T(const T&)调用对象 T?
- 将另一个类的对象传递到当前类C++的构造函数中(不是成员初始化)
- 如何将我编写的对象传递到另一个类的构造函数中?
- 使用向量初始化参数化构造函数的对象数组
- 在C++中将对象从另一个类传递到另一个类的构造函数?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 构造函数对象赋值是否泄漏内存
- gcc中不可移动构造函数对象的std::函数