Tru*_*pti 9 c++ this this-pointer
我需要理解this
指针概念,最好用一个例子.
我是C++的新手,所以请使用简单的语言,以便我能更好地理解它.
this
是指向其类实例的指针,可用于所有非静态成员函数.
如果您声明了一个具有私有成员foo
和方法的类bar
,foo
则可以bar
通过this->foo
但不能通过"外部人员"进行通过instance->foo
.
该this
指针是一类用来指本身.返回对自身的引用时通常很方便.使用赋值运算符查看原始典型示例:
class Foo{
public:
double bar;
Foo& operator=(const Foo& rhs){
bar = rhs.bar;
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
有时如果事情变得混乱,我们甚至会说
this->bar = rhs.bar;
Run Code Online (Sandbox Code Playgroud)
但在这种情况下通常被视为过度杀伤.
接下来,当我们构造我们的对象时,包含的类需要引用我们的对象来运行:
class Foo{
public:
Foo(const Bar& aBar) : mBar(aBar){}
int bounded(){ return mBar.value < 0 ? 0 : mBar.value; }
private:
const Bar& mBar;
};
class Bar{
public:
Bar(int val) : mFoo(*this), value(val){}
int getValue(){ return mFoo.bounded(); }
private:
int value;
Foo mFoo;
};
Run Code Online (Sandbox Code Playgroud)
因此this
用于将我们的对象传递给包含的对象.否则,没有this
如何表示我们在里面的课程?类定义中没有对象的实例.这是一个阶级,而不是一个对象.
归档时间: |
|
查看次数: |
3516 次 |
最近记录: |