c++中也是有this的,因为java中有呀。其实c++中的this指针和java中的是一样的。我们定义一个类,当类被实例化以后,总是有一个this指针指向该实例的。因此不论你见或不见,它就在那里。仅仅注意,this是个指针而已。java的封装比较厉害,直接把this封装成了一个所谓的引用。
我们举个例子来说明this指针的使用吧。
#include <iostream>
using namespace std;
class base
{
private:
int x;
int y;
public:
base(int x,int y);
~base();
friend void prt(base b);
};
base::base(int x,int y)
{
this->x = x;
this->y = y;
}
base::~base()
{
cout << "destructing..." << endl;
}
void prt(base p)
{
cout << p.x << endl;
cout << p.y << endl;
}
void main()
{
base ba(1,2);
prt(ba);
}
我们在上面的例子中定义了一个base类,该类有成员变量x,y,在构造函数的形参中也有x,y,为了区分这两对变量,我们用了this指针,并用其友元函数打印出来。关于this,我在java中也没发现其他更有意义的用法,因此类比下c++,就先记录到这里了。
super关键字,我在java中有用到,主要是通过子类来引用父类的成员以及方法。但是在c++中没有这个关键字。没有这个关键字但是不代表没有类似的功能。所以我学习了一下c++中子类调用父类的方法。
#include <iostream>
using namespace std;
class base
{
private:
int x;
int y;
public:
base(int x=2,int y=3);
~base();
void prt();
friend void prt(base b);
};
class derive : public base
{
public:
void sprt();
};
void derive::sprt()
{
base::prt();
}
base::base(int x,int y)
{
this->x = x;
this->y = y;
}
base::~base()
{
cout << "destructing..." << endl;
}
void base::prt()
{
cout << this->x * this->y << endl;
}
void prt(base p)
{
cout << p.x << endl;
cout << p.y << endl;
}
void main()
{
derive *d = new derive();
d->sprt();
}
我们在上个例子的基础上,实现了子类,在子类的sprt函数中,调用父类的prt函数,来打印成员变量。调用的方式很简单。基类::func()即可。
关于this和"super"就先记录这么多了。