如复制构造函数中
#include
using namespace std;
class Data {
public:
Data(int a) { x = a; }
Data(const Data& r)//调用别对象的函数
{
x = r.x;
}
void s() { cout << x << endl; }
private:
int x;
};
int main()
{
Data a(1);
Data b(a);
cout << “b中的x=”; b.s();
cout << “a中的x=”; a.s();
return EXIT_SUCCESS;
}
输出结果为
或在普通的成员函数中
#include
using namespace std;
class Data {
public:
Data(int a=0) { x = a; }
void s (const Data& r)//调用别对象的函数
{
x = r.x;
}
void getx() { cout << x << endl; }
private:
int x;
};
int main()
{
Data a(1);
Data b;
cout << “b中的x=”; b.getx();
b.s(a);
cout << “调用s函数后 b中的x=”; b.getx();
return EXIT_SUCCESS;
}
输出结果为
总的来说,想要同类的不同对象可以相互访问成员,类的定义中就应该存在一个形参里有对象或对象引用或对象指针的成员函数。



