• 闪存
• 博客
• 发言 小组
• 投递 新闻
• 提问 博问
• 添加 收藏
• 发布 招聘
• 文库

# 如何获取调用方法的实例

0 悬赏园豆：20 [已解决问题] 解决于 2012-09-11 20:25 class A{

void Method(){

//do sth.

}

}

A a1=new A();

a1.Method();

A a2=new  A();

a2.Method();

0

```class A
{
public void Method()
{
//this 代表当前实例
}
}```

```A a1 = new A();
A a2 = a1;
A a3 = a1;
A a4 = a1;...A a99 = a1;a99.Method();```

`new A().Method();`

0

```class A{
public string name;
void Method(){
//do sth.
Console.Wirte("我是"+this.name);
}
}

A a1=new A();
a1.name="张三";
a1.Methode();

A a2=new A();
a2.name="李四";
a2.Method();```

你理解错了，楼主的意思是要返回得到 "a1" 或者"a2"，当然可以在构造函数里面将a1.name幅值成"a1"，这样就可以用this.name查看。但是这样就需要程序员自己写。

感觉有点像反射机制的逆过程······

关注···

@汪浩瀚:

0

chenping2008 | 园豆：9836 (大侠五级) | 2012-09-11 13:09
0

class A{

void Method(){

this // 这就是调用该方法的实例，但是没有办法知道该实例是 a1 还是 a2.

}

}

Launcher | 园豆：45045 (高人七级) | 2012-09-11 13:12
0

#include <iostream>
using namespace std;

class A
{
public:
A(){ type = 0;};
virtual ~A(){};

public:
void myFun();
void setType(char type);

private:
char type;
};

void A::myFun()
{
switch(type)
{
case 1:
{
//do a1 sth;
break;
}
case 2:
{
//do a2 sth;
break;
}
default:
break;
}
}
int main(int argc, char **argv) {

A a1 = new A();
a1.setType(1);
a1.myFun();
A a2 = new A();
a2.setType(2);
a2.myFun();
return 0;
}

void myFun(void)

{
cout << this << endl;//显示两个对象调用的实例对象的地址

}

0

您需要登录以后才能回答，未注册用户请先注册
{"ft_lang_label":"__label__zh","ft_lang_prob":0.7437316,"math_prob":0.66820276,"size":1640,"snap":"2020-34-2020-40","text_gpt3_token_len":957,"char_repetition_ratio":0.12897311,"word_repetition_ratio":0.010309278,"special_character_ratio":0.32682925,"punctuation_ratio":0.23841059,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.951562,"pos_list":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],"im_url_duplicate_count":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-09-26T03:38:12Z\",\"WARC-Record-ID\":\"<urn:uuid:3e862632-5a80-4015-a050-2f5c74ba234c>\",\"Content-Length\":\"42490\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:615c98e3-970d-461b-b908-90909cf23719>\",\"WARC-Concurrent-To\":\"<urn:uuid:f8ade3f9-3cef-4b4a-9abf-5762815541a2>\",\"WARC-IP-Address\":\"120.55.196.147\",\"WARC-Target-URI\":\"https://q.cnblogs.com/q/41083/\",\"WARC-Payload-Digest\":\"sha1:E73LYBWZLOV462SJVPWQRKSV2NASY2DB\",\"WARC-Block-Digest\":\"sha1:QYVIXVQPH7Z44UJH3QL27K4GWJSZ56NS\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-40/CC-MAIN-2020-40_segments_1600400232211.54_warc_CC-MAIN-20200926004805-20200926034805-00642.warc.gz\"}"}