提交 c1fef3a5 编写于 作者: W wsb

重载比较运算符示范

上级 b13d2e11
......@@ -3,4 +3,4 @@ project(CPP_11_HeavyLoad)
set(CMAKE_CXX_STANDARD 11)
add_executable(CPP_11_HeavyLoad main.cpp test.cpp test.h operatorDemo.cpp operatorDemo.h minusOperator.cpp minusOperator.h)
add_executable(CPP_11_HeavyLoad main.cpp test.cpp test.h operatorDemo.cpp operatorDemo.h minusOperator.cpp minusOperator.h relationOperator.cpp relationOperator.h)
......@@ -2,6 +2,11 @@
#include "test.h"
#include "operatorDemo.h"
#include "minusOperator.h"
#include "relationOperator.h"
#include <string>
#include <iostream>
using namespace std;
int main() {
......@@ -13,7 +18,7 @@ int main() {
test->max("字符串", 12, 12);
cout << max1 << "," << max2 << endl;
//重载+号运算符
//重载+号运算符: 其他符号的- ,* , / 重载与加号类型
operatorDemo op1(12, 12, 12), op2(34, 23, 14); //申明两个类对象并给出初始值
op1.print();
op2.print();
......@@ -30,5 +35,10 @@ int main() {
b.print();
//重载比较运算大于号,用于比较两个对象是否相等
relationOperator relationOperator(12,34), relationOperator1(99,23);
string max= relationOperator>relationOperator1? "大于" : "不大于";
cout<<max<<endl;
return 0;
}
//
// Created by 11010 on 2023/4/8.
//
#include "relationOperator.h"
void relationOperator::print() {
cout<<"长:"<<len<<",宽:"<<width<<endl;
}
relationOperator::relationOperator(int l, int w):len(l),width(w) {
}
bool relationOperator::operator>(const relationOperator &ro) {
//只要有一个大于就返回true
if (len>ro.len) return true;
if (width>ro.width) return true;
//均不大于返回false
return false;
}
//
// Created by 11010 on 2023/4/8.
//
#ifndef CPP_11_HEAVYLOAD_RELATIONOPERATOR_H
#define CPP_11_HEAVYLOAD_RELATIONOPERATOR_H
#include <iostream>
using namespace std;
class relationOperator {
public:
int len;
int width;
void print(); //打印信息
relationOperator(int l,int w);
bool operator> (const relationOperator &ro); //重载小于运算符
};
#endif //CPP_11_HEAVYLOAD_RELATIONOPERATOR_H
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册