例子:
将*重载为友元函数,->重载函数返回一个重载了->的结构体变量的引用。
#include <iostream>
using namespace std;
struct stru
{
stru(string s="结构体stru"):s(s)
{}
stru* operator->()
{
return this;
}
string s;
};
class Integer
{
Integer(int x=666)
{
p=new int{x};
}
~Integer()
{
if(p)
delete p;
if(ps)
delete ps;
}
friend int operator*(Integer &i);
stru& operator->()
{
return *ps;
}
friend int main();
int *p=nullptr;
stru *ps=new stru;
};
int operator*(Integer &i)
{
return *i.p;
}
int main()
{
Integer i,i2(12345);
cout<<*i<<endl;
cout<<*i2<<endl;
cout<<i->s<<endl;
i2->s="结构体stru的成员s";
cout<<i2->s<<endl;
return 0;
}
将*重载为友元函数,->重载函数返回一个重载了->的结构体变量的引用。
#include <iostream>
using namespace std;
struct stru
{
stru(string s="结构体stru"):s(s)
{}
stru* operator->()
{
return this;
}
string s;
};
class Integer
{
Integer(int x=666)
{
p=new int{x};
}
~Integer()
{
if(p)
delete p;
if(ps)
delete ps;
}
friend int operator*(Integer &i);
stru& operator->()
{
return *ps;
}
friend int main();
int *p=nullptr;
stru *ps=new stru;
};
int operator*(Integer &i)
{
return *i.p;
}
int main()
{
Integer i,i2(12345);
cout<<*i<<endl;
cout<<*i2<<endl;
cout<<i->s<<endl;
i2->s="结构体stru的成员s";
cout<<i2->s<<endl;
return 0;
}