18、(1)对象指针做函数参数
a.对象指针和对象引用
b.数组
c.常类型
d.子对象和对对象
优点:
a.实现传址调用。可在被调用函数中改变调用函数的参数对象的值,实现函数之间的信息传递;
b.使用对象指针实参仅将对象的地址值传递给形参,而不是进行副本的拷贝,这样可以提高运
行效率,减少时间开销;
#include<iostream.h>
class M{
public:
M() { x=y=0; }
M(int i,int j) { x = i;y = j; }
void copy(M *m);
void setxy(int i,int j){ x = i;y = j;}
void print() { cout<<x<<","<<y<<endl; }
private:
int x,y;
};
void M::copy(M *m)
{
x = m->x;
y = m->y;
}
void fun(M m1,M *m2)
{
m1.setxy(1,2);
m2->setxy(3,4);
}
void main()
{
M p(5,7),q;
q.copy(&p);
fun(p,&q);
p.print(); // 5 7 而不是 1 2
//原因在于:传递对象不能改变其值,只能传递对象指针才有用
q.print();
}
(2)对象引用用作函数参数
#include<iostream.h>
class M
{
public:
M() { x = y = 0;}
M(int i,int j) { x = i;y = j;}
void copy(M &m);
void setxy(int i,int j) { x = i;y = j;}
void printf() { cout<<x<<","<<y<<endl;}
private:
int x,y;
};
void M::copy(M &m)
{
x = m.x;
y = m.y;
}
void fun(M m1,M &m2){
m1.setxy(5,6);
m2.setxy(7,8);
}
void main()
{
M m1(1,2),m2(3,4);
m1.copy(m2);
m1.printf();
m2.printf();
fun(m1,m2);
m1.printf(); //m1为实际对象,所以无法改变。
m2.printf(); //m2为引用类型,所以可以改变。
};
19、this指针
#include<iostream.h>
class A{
public:
A() { a=b=0; }
A(int i,int j) { a = i;b = j;}
void copy(A &aa);
void print() { cout<<a<<","<<b<<endl; }
private:
int a,b;
};
void A::copy(A &aa)
{
if(this == & aa)
this->a = aa.a; //this指针指向正在被某个成员函数操作的对象。
(*this).b = aa.b; //*this标识调用成员函数的对象。
}
void main()
{
A c(3,4),d;
d.copy(c);
d.print();
}
总结:
a.this指针指向正在被某个成员函数操作的对象
b.*this标识调用成员函数的对象
a.对象指针和对象引用
b.数组
c.常类型
d.子对象和对对象
优点:
a.实现传址调用。可在被调用函数中改变调用函数的参数对象的值,实现函数之间的信息传递;
b.使用对象指针实参仅将对象的地址值传递给形参,而不是进行副本的拷贝,这样可以提高运
行效率,减少时间开销;
#include<iostream.h>
class M{
public:
M() { x=y=0; }
M(int i,int j) { x = i;y = j; }
void copy(M *m);
void setxy(int i,int j){ x = i;y = j;}
void print() { cout<<x<<","<<y<<endl; }
private:
int x,y;
};
void M::copy(M *m)
{
x = m->x;
y = m->y;
}
void fun(M m1,M *m2)
{
m1.setxy(1,2);
m2->setxy(3,4);
}
void main()
{
M p(5,7),q;
q.copy(&p);
fun(p,&q);
p.print(); // 5 7 而不是 1 2
//原因在于:传递对象不能改变其值,只能传递对象指针才有用
q.print();
}
(2)对象引用用作函数参数
#include<iostream.h>
class M
{
public:
M() { x = y = 0;}
M(int i,int j) { x = i;y = j;}
void copy(M &m);
void setxy(int i,int j) { x = i;y = j;}
void printf() { cout<<x<<","<<y<<endl;}
private:
int x,y;
};
void M::copy(M &m)
{
x = m.x;
y = m.y;
}
void fun(M m1,M &m2){
m1.setxy(5,6);
m2.setxy(7,8);
}
void main()
{
M m1(1,2),m2(3,4);
m1.copy(m2);
m1.printf();
m2.printf();
fun(m1,m2);
m1.printf(); //m1为实际对象,所以无法改变。
m2.printf(); //m2为引用类型,所以可以改变。
};
19、this指针
#include<iostream.h>
class A{
public:
A() { a=b=0; }
A(int i,int j) { a = i;b = j;}
void copy(A &aa);
void print() { cout<<a<<","<<b<<endl; }
private:
int a,b;
};
void A::copy(A &aa)
{
if(this == & aa)
this->a = aa.a; //this指针指向正在被某个成员函数操作的对象。
(*this).b = aa.b; //*this标识调用成员函数的对象。
}
void main()
{
A c(3,4),d;
d.copy(c);
d.print();
}
总结:
a.this指针指向正在被某个成员函数操作的对象
b.*this标识调用成员函数的对象