感觉这个功能还蛮有意思的,就是不知道什么情况下会用到
#include
using namespace std;
class Example
{
private:
int feet;
int inches;
public:
Example();
Example(int ft);
~Example() {};
void show_in() const;
void show_ft() const;
void use_ptr() const;
};
Example::Example()
{
this->feet = 0;
this->inches = 0;
}
Example::Example(int ft)
{
this->feet = ft;
this->inches = 12 * ft;
}
void Example::show_in() const
{
cout << this->inches << " inches\n";
}
void Example::show_ft() const
{
cout << this->feet << " feet\n";
}
void Example::use_ptr() const
{
Example yard(3);
int Example::* pt;
pt = &Example::inches;
cout << "set pt to &Example::inches:\n";
cout << "this->*pt: " << this->*pt << endl;
cout << "yard.*pt: " << yard.*pt << endl;
pt = &Example::feet;
cout << "set pt to &Example::feet:\n";
cout << "this->*pt: " << this->*pt << endl;
cout << "yard.*pt: " << yard.*pt << endl;
void (Example:: * pf)() const;
pf = &Example::show_in;
cout << "set pf to &Example::show_in:\n";
cout << "using (this->*pf)(): ";
(this->*pf)();
cout << "using (yard.*pf)(): ";
(yard.*pf)();
}
int main()
{
Example car(15);
Example van(20);
Example garage;
cout << "car.use_ptr() output:\n";
car.use_ptr();
cout << "\nvan.use_ptr() output:\n";
van.use_ptr();
return 0;
}
car.use_ptr() output:
set pt to &Example::inches:
this->*pt: 180
yard.*pt: 36
set pt to &Example::feet:
this->*pt: 15
yard.*pt: 3
set pf to &Example::show_in:
using (this->*pf)(): 180 inches
using (yard.*pf)(): 36 inches
van.use_ptr() output:
set pt to &Example::inches:
this->*pt: 240
yard.*pt: 36
set pt to &Example::feet:
this->*pt: 20
yard.*pt: 3
set pf to &Example::show_in:
using (this->*pf)(): 240 inches
using (yard.*pf)(): 36 inches