C++|作业训练-运算符重载

问题背景1

一般的彩色数字图像由 (红), (绿), (蓝)三个通道组成,根据下述的运算规则可以将RGB彩色图像转换为单通道的灰度图像。
g ( r , g , b ) = 0.299 × r + 0.587 × g + 0.114 × b g(r,g,b)=0.299\times r+0.587\times g+0.114\times b g(r,g,b)=0.299×r+0.587×g+0.114×b
上式中 即是由 计算灰度 的函数。请重构运算符“()”,实现上述转换过程。一般情况下, 取值为[0, 255]范围内的整数。

操作步骤

  1. 导入标准库头文件与String库。
  2. 创建一个color类
  3. 写好数据初始化
  4. 重载运算符函数实现
  5. 在主函数中调用
  6. 输出显示

代码实现

#include<iostream>
#include<string>
using namespace std;
class color {
public:
	float r, g, b;
	color() { r = 0.0; g = 0.0; b = 0.0; }
	color(float r,float g, float b) :r(r), g(g), b(b) {}

};
color operator()(const color & col1, const color & col2 )
{
	return color(col1.r*col2.r, col1.g * col2.g, col1.b * col2.b );
}
int main() {
	float r, g, b;
	cout << "请输入R/G/B值:" << endl; 
	cin >> r >> g >> b;
	if (r <0||r>255|| g < 0 || g>255|| b < 0 || b>255)
	{
		cout << "ERROR!请输入[0:255]的R/G/B值!" << endl; //控制数据合法
		
	}
	else
	{
		color col1(r, g, b);
		color col2(0.299, 0.587, 0.114);
		cout << "单通道的灰度图像的R/G/B值是:" << endl;
		color C = operator()(col1, col2);
		cout << "R:" << C.r << endl;
		cout << "G:" << C.g << endl;
		cout << "B:" << C.b << endl;
		return 0;
	}
}


问题背景2

三维空间中的点可以看作是三维向量,两个三维向量相减可以用这两点之间的距离来表示,构造一个三维向量类multVector,重载“-”减号运算符计算两个三维向量之间的距离。

操作步骤

  1. 导入标准库头文件与String库以及cmath库。
  2. 创建一个multVector类
  3. 写好数据初始化与运算符重载函数声明
  4. 重载运算符函数实现
  5. 在主函数中调用
  6. 输出显示

代码实现

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
class multVector {
private:
	float x, y, z;
public:
    multVector() { x = 0.0, y = 0.0, z = 0.0; }
    multVector(float x, float y, float z) :x(x), y(y), z(z) {}
	float operator- (const multVector& m)
	{
		return sqrt((this->x - m.x) * (this->x - m.x) + (this->y - m.y) * (this->y - m.y) + (this->y - m.z) * (this->y - m.z));
	}
};
int main()
{
    float x1, y1, z1;
    float x2, y2, z2;
    cout << "请输入第一个点的坐标" << endl;
    cin >> x1 >> y1 >> z1;
    multVector m1(x1, y1, z1);
    cout << "请输入第二个点的坐标" << endl;
    cin >> x2 >> y2 >> z2;
    multVector m2(x2, y2, z2);
    cout << "两点之间的距离是:" << endl;
    cout << m2 - m1 << endl;
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值