获取对象的名称 [英] getting the name of an object
问题描述
你好,
我写了一个简单的树类,想要创建一个显示
完整树及其所有节点的函数。
我的问题是我不知道如何获取对象的名称。我想要
来获得类似
class Tree
{
char *姓名;
树(){
name = this-> variable_that_contains_name_of_object;
}
}
树一;
cout<< one.name;
导致输出:
一个
感谢您的帮助
Thomas
Hi there,
I''ve written a simple tree class and want to make a function that shows a
full tree with all its nodes.
My problem is that I do not know how to get the name of an object. I''d like
to have something like
class Tree
{
char *name;
Tree() {
name = this->variable_that_contains_name_of_object;
}
}
Tree one;
cout << one.name;
that results in the output:
one
Thanks for help
Thomas
推荐答案
Thomas Baier< th **** @ tho-bai.de>在留言中写道
新闻:3f ********************** @ newsread2.arcor-online.net ...
Thomas Baier <th****@tho-bai.de> wrote in message
news:3f**********************@newsread2.arcor-online.net...
你好,
我写了一个简单的树类,想要创建一个显示所有节点的完整树的函数。
我的问题是我不知道如何获取对象的名称。我要
喜欢有类似
类的东西
{
char * name;
树(){
name =
this-> variable_that_contains_name_of_object; }
}
树一;
cout<< one.name;
导致输出:
一个
Hi there,
I''ve written a simple tree class and want to make a function that shows a
full tree with all its nodes.
My problem is that I do not know how to get the name of an object. I''d like to have something like
class Tree
{
char *name;
Tree() {
name = this->variable_that_contains_name_of_object; }
}
Tree one;
cout << one.name;
that results in the output:
one
这不能''直接'',因为一旦代码编译成了b $ b,就没有对象的名称了。一切
是一个地址或一个偏移量。
但是,您可以创建一个数据成员来存储
你的' 'name''作为一个字符串。
#include< string>
class X
{
std :: string m_name;
public:
X(const std :: string& n):m_name(n){}
const std :: string& name()const {return m_name; }
};
int main()
{
X obj(one ); / *使用一个的名称创建对象* /
std :: string s(obj.name()); / *检索对象的名称和商店
在另一个字符串中* /
返回0;
}
-Mike
This cannot be done ''directly'', since once the code is
compiled, there are no more ''names'' of objects. Everything
is an address or an offset.
You could, however, create a data member which you store
your ''name'' in as a string.
#include <string>
class X
{
std::string m_name;
public:
X(const std::string& n) : m_name(n) {}
const std::string& name() const { return m_name; }
};
int main()
{
X obj("one"); /* create object with ''name'' of "one" */
std::string s(obj.name()); /* retrieve object''s name and store
in another string */
return 0;
}
-Mike
没有其他方法,没有将构造函数的名称作为
参数?
Isn''t there another way, without giving the name to the constructor as an
argument?
" Thomas Baier" <第**** @ tho-bai.de>在留言新闻中写道:3f *********************** @ newsread4.arcor-online.net ...
"Thomas Baier" <th****@tho-bai.de> wrote in message news:3f***********************@newsread4.arcor-online.net...
Isn'还有另一种方法,没有将构造函数的名称作为
参数?
Isn''t there another way, without giving the name to the constructor as an
argument?
否。语言无法获取标识符名称。一般来说,他们在运行时不存在
。
No. The language provides no way to get the identifier names. In general, they
do not exist at runtime.
这篇关于获取对象的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!