day4 C++
作业
取余运算符重载
#include <iostream>
using namespace std;
class Stu
{
//使用friend关键字是全局函数operator%可以访问类私有成员变量
friend const Stu operator%(const Stu &other1,const Stu &other2);
private:
int a;
int b;
public:
Stu(){}
Stu(int a,int b):a(a),b(b){}
//成员函数完成取余
// const Stu operator%(const Stu &other) const
// {
// Stu temp;
// temp.a=a%other.a;
// temp.b=b%other.b;
// return temp;
// }
void show()
{
cout << "a=" << a <<endl;
cout << "b=" << b <<endl;
}
};
//全局函数实现取余
const Stu operator%(const Stu &other1,const Stu &other2)
{
Stu temp;
temp.a=other1.a % other2.a;
temp.b=other1.b % other2.b;
return temp;
}
int main()
{
Stu s1(2,4);
Stu s2(3,3);
Stu s3=s1%s2;
s3.show();
return 0;
}
乘法运算符重载
#include <iostream>
using namespace std;
class Stu
{
friend const Stu operator*(const Stu &other1,const Stu &other2);
private:
int a;
int b;
public:
Stu(){}
Stu(int a,int b):a(a),b(b){}
// const Stu operator*(const Stu &other) const
// {
// Stu temp;
// temp.a=a*other.a;
// temp.b=b*other.b;
// return temp;
// }
void show()
{
cout << "a=" << a <<endl;
cout << "b=" << b <<endl;
}
};
const Stu operator*(const Stu &other1,const Stu &other2)
{
Stu temp;
temp.a=other1.a * other2.a;
temp.b=other1.b * other2.b;
return temp;
}
int main()
{
Stu s1(2,4);
Stu s2(3,3);
Stu s3=s1*s2;
s3.show();
return 0;
}