C++参照、友関数、演算子リロード
2442 ワード
void Printf(Base & a,Base *ap)
{
int temp = 10;
&a = &temp;// ,
a = 10;// , 。
ap = &temp;// , , 。
}
友元関数:
友元関数とクラスのメンバー関数の違い:
#include
class Student
{
private:
int x;
int y;
public:
Student(int x,int y)
{
this->x = x;
this->y = y;
}
friend void Printf1(Student* p);
friend void Printf2(const Student& p);
};
// ,
void Printf1(Student* p)
{
printf("%d %d
",p->x,p->y);
}
void Printf2(const Student& p) // const ,
{
printf("%d %d
",p.x,p.y);
}
int main(int argc,char *argv[])
{
Student s(1,2);
Printf1(&s);
Printf2(s);
return 0;
}
演算子の再ロード
#include
class Number
{
private:
int lowValue;
int highValue;
public:
Number(int lowValue,int highValue)
{
this->lowValue = lowValue;
this->highValue = highValue;
}
void Print();
//void Plus();//plus int ++ , , ++ , .
Number operator++();//int++ int, / 。
Number operator+(const Number& p);
friend bool operator>(const Number& p1,const Number& p2);
friend bool operatorlowValue += p.lowValue;
this->highValue += p.highValue;
return *this;
}
bool operator>(const Number& p1,const Number& p2)
{
if((p1.lowValue > p2.lowValue) && (p1.highValue > p2.highValue))
return true;
else
return false;
}
bool operatorn1)
printf("> true
");
else
printf("> false
");
if(n