zoukankan      html  css  js  c++  java
  • 运算符中的二元重载,为什么要调用友元函数而不是全局函数的问题

    #include <iostream>
    
    using namespace std;
    //实现运算符的重载
    class A
    {
    public:
    	A(int real=0,int imaginary=0 )
    	{
    		this->real=real;
    		this->imaginary=imaginary;
    	}
    
    	void printf()
    	{
    		cout<<this->real<<" + "<<this->imaginary<<"j
    ";
    	}
    	friend A operator+(A &a1,A &a2);//这里的友元函数是取决于私有属性
    public:
    	A  operator-(A &t1)//这个一定要表明类型的,因为这不是构造函数,所以必须有类型。
    	{
    		this->real=this->real-t1.real;
    		this->imaginary=this->imaginary-t1.imaginary;
    		return * this;
    	}
    private:
    	int real;
    	int imaginary;
    };
    
    A operator+(A &a1,A &a2)
    {
    	A tem(a1.real+a2.real , a1.imaginary+a2.imaginary);
    	return tem;
    }
    
    int main()
    {
    	A c1(1,2), c2(3,4);
    	A  c3;
    	c3=c1+c2;
    	c3.printf();
    	 
    //	A t1;
    	//c1.operator-(c2);
    	A c4 =c1-c2;
    	c4.printf();
    	system("pause");
    	return 0;
    }
    

      因为,类的成员变量一般是私有的,所以,类的外部除了友元函数其他函数都不能调用类的私有变量。

  • 相关阅读:
    DbgPrint格式 输出
    string 类常用函数[转]
    pragma warning[转]
    连接符
    ubuntu ftp server
    关于dex

    Topology中各函数调用顺序
    C# 错误捕捉
    操作word,Excel,PPT
  • 原文地址:https://www.cnblogs.com/xiaochige/p/6581920.html
Copyright © 2011-2022 走看看