zoukankan      html  css  js  c++  java
  • C++之类的比較运算符的重载

    比較运算符的重载通常有两种方式:

    第一:作为成员函数重载

    曾经几章的Student类为例:

    <span style="font-family:Microsoft YaHei;font-size:18px;">class Student{
    private:
    	string name;
    	int age;
    	float score;
    	//const成员变量
    	const int max_length;
    	//定义静态成员变量
    	static int number; 
    	static float total;
    public:
    	//Student(string name,int age,float score);
    	//有const成员变量,必须有參数初始化列表,
    	Student(string name,int age,float score):name(name),age(age),score(score),max_length(3){
    		number++;
    		total += score;
    	}
    	//拷贝构造函数中,const成员变量的初始化,用初始化列表
    	Student(const Student & s):max_length(3){
    		this ->name = s.name;
    		this ->age = s.age;
    		this ->score = s.score;
    		number++;
    		total += score;
    	};
    	~Student();
    	void setName(string n);
    	string getName()const;
    	void setAge(int a);
    	int getAge() const;
    	void setScore(float s);
    	float getScore() const;
    	void say() const;
    	static float getAverage();
    	
    	//运算符的重载
    	bool operator== (const Student &s) const;
    	//用友元函数重载等于 运算符
    	//friend bool operator== (const Student &s,const Student&s1);
    };
    </span>
    这里能够把(opetator==)理解为"成员函数名"。

    bool Student::operator==(const Student &s) const {
    	return this->name == s.name && this->age == s.age && this ->score == s.score;
    }
    

    第二:作为友元函数重载

     bool operator== (const Student &s,const Student&s1){
    	 return (s.age == s1.age && s.name == s1.name && s.score == s1.score);
    }
    
    



  • 相关阅读:
    预备作业03 20162308马平川
    预备作业02 20162308 马平川
    预备作业01
    采用dlopen、dlsym、dlclose加载动态链接库
    FastCGI协议分析
    Fastcgi协议定义解释与说明
    linux exec函数族
    进程通信---FIFO
    FTP协议及工作原理详解
    HTTP协议详解
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/7159125.html
Copyright © 2011-2022 走看看