C++参照、友関数、演算子リロード

2442 ワード

  • 参照およびポインタは、最下位アセンブリフェーズでは何の違いもなく、アドレス伝達である.
  • は異なります.ポインタにはアドレスが乱される可能性がありますが、参照は起こりません.参照の値を変更することは、実際には変数のアドレスではなく、変数のアドレスの値を変更することです.
  • 参照はC++に特有のタイプです.
  • 参照タイプは1回のみ付与でき、再付与できません.
  • 参照は変数の別名にすぎません.
  • 参照は、コンパイラがメンテナンスするポインタと理解できるが、スペースを占有しない.
  • 参照を使用すると、ポインタのようにオブジェクトの内容にアクセスし、変更できますが、より安全です.
  • void Printf(Base & a,Base *ap)
    {
    	int temp = 10;
    	&a = &temp;//  ,        
    	a = 10;//  ,           。
    	ap = &temp;//  ,        ,        。
    }

    友元関数:
  • は、この関数にプライベートメンバーにアクセスする権限です.
  • 演算子をリロードする場合は、友元を使用する必要があります.
  • の2つのクラスがデータを共有する場合.

  • 友元関数とクラスのメンバー関数の違い:
  • メンバー関数にはthisポインタがありますが、友元関数にはthisポインタがありません.
  • 友元関数は継承できません.父の友达が必ずしも息子の友达ではないように.
  • #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; }

    演算子の再ロード
  • は関数置換です.
  •  .   ::   ?:sizeof#はリロードできません.残りはリロードできます.
  • では、常にリロードする演算子が必要です.
  • #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