return *this的使用, 怎么改呢?

西兹兹 2005-08-26 07:25:09
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
#include<conio.h>
#include<vector>
#include<utility> // pair 类
#include<cstddef> // sizeof
#include<list>//list类
#include<memory> // anto_pr,自动new,delete
#include<algorithm>// copy()泛型算法
#include<iterator> //
using namespace std;
class Screen{
public:
Screen(int height = 1,int width =2);
Screen& output1() const;
void output2() const;
private:
int _h, _w;
};//每个类的成员函数都含有一个指向被调用对象的指针,即是this,类的不同对象有不同的指针
int main()
{
Screen *p = new Screen;
p->output1().output2();
getch();
return 0;
}
Screen::Screen(int height ,int width)
{
this->_h = height;
(*this)._w= width;
}
Screen& Screen::output1() const
{
cout<<"output1:"<<endl
<<_h<<endl
<<_w<<endl;
return *this;
}
void Screen::output2() const
{
cout<<"output1:"<<endl
<<_h<<endl
<<_w<<endl;
}
...全文
227 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
oosky2004 2005-08-27
  • 打赏
  • 举报
回复
};//每个类的成员函数都含有一个指向被调用对象的指针,即是this,类的不同对象有不同的指针
------------------------------------------------------------

还有你这句话不知道说的什么意思?

oosky2004 2005-08-27
  • 打赏
  • 举报
回复
Screen object;
object.output1();
object.output2();
我知道这样可以实现,但是我想用return *this, 啊
---------------------------------------------------
this = &object.
oosky2004 2005-08-27
  • 打赏
  • 举报
回复
Screen::Screen(int height ,int width)
{
this->_h = height;
(*this)._w= width;
}
Screen& Screen::output1() const
{
cout<<"output1:"<<endl
<<_h<<endl
<<_w<<endl;
return *this;
}
--------------------------------------------------------
晕了。楼主的类为什么要加一个this呢,这些都是多此一举,不必要的。
this->_h = height;
(*this)._w= width;
象这两句,this完全可以去掉。
xinxiakk 2005-08-26
  • 打赏
  • 举报
回复
倒了,你自己写的这个screen类好像就可以

这个类好熟悉,好像在哪里看过
fangrk 2005-08-26
  • 打赏
  • 举报
回复
Screen object;
object.output1().output2();
西兹兹 2005-08-26
  • 打赏
  • 举报
回复
Screen object;
object.output1();
object.output2();
我知道这样可以实现,但是我想用return *this, 啊
foochow 2005-08-26
  • 打赏
  • 举报
回复
不懂楼主的意思
bugebear3 2005-08-26
  • 打赏
  • 举报
回复
Screen object;
object.output1();
object.output2();
西兹兹 2005-08-26
  • 打赏
  • 举报
回复
p->output1().output2();
我想创建类的一个对象来调用output1().和output2().
xinxiakk 2005-08-26
  • 打赏
  • 举报
回复
不太明白你的意思,你想改成什么样子,使它具有什么功能?
zyfire88 2005-08-26
  • 打赏
  • 举报
回复
return *this返回当前对象
西兹兹 2005-08-26
  • 打赏
  • 举报
回复
我知道啊, 我想知道怎么改
djfu 2005-08-26
  • 打赏
  • 举报
回复
*this 相当于 this->

return *this, 返回自身对象。

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧