问题背景1
一般的彩色数字图像由 (红), (绿), (蓝)三个通道组成,根据下述的运算规则可以将RGB彩色图像转换为单通道的灰度图像。 上式中 即是由 计算灰度 的函数。请重构运算符“()”,实现上述转换过程。一般情况下, 取值为[0, 255]范围内的整数。 ## 操作步骤
- 导入标准库头文件与String库。
- 创建一个color类
- 写好数据初始化
- 重载运算符函数实现
- 在主函数中调用
- 输出显示
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #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,重载“-”减号运算符计算两个三维向量之间的距离。
操作步骤
- 导入标准库头文件与String库以及cmath库。
- 创建一个multVector类
- 写好数据初始化与运算符重载函数声明
- 重载运算符函数实现
- 在主函数中调用
- 输出显示
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #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; }
|