1、类的成员
1.1 定义一个类
定义一个类的时候,可以将类的定义和实现分别定义在各自的文件中。类的定义使用头文件的形式,通俗来说,即 .h
类型的文件。类的实现使用 .cpp
类型的文件。如果需要给定义的类指定一个命名空间,那么我们可以直接在头文件中指定。同一个命名空间的代码块可以定义多个类,也可以定义结构体。
#pragma once
#include <opencv2/opencv.hpp>
namespace ImageEngine
{
// 定义一个类
class ImageFilter
{
// 类的 public 变量和方法的声明区域
public:
ImageFilter(const cv::Mat &OriginMat);
cv::Mat PrintFilter(const cv::Mat &OriginMat);
cv::Mat PictureFilter(const cv::Mat &OriginMat);
cv::Mat GuidedFilter(const cv::Mat &GuidedMat, const cv::Mat &FilterMat, int Radius, double EPS);
cv::Mat ContrastFilter(const cv::Mat &OriginMat, float Intensity /*-0.5f - 1.0*/);
// 类的 private 变量和方法的声明区域
private:
cv::Mat OriginMat_;
};
}
#include "ImageFilter.h"
#include <opencv2/ximgproc.hpp>
namespace ImageEngine
{
// 构造函数的实现,注意使用的 ::
ImageFilter::ImageFilter(const cv::Mat &OriginMat)
: OriginMat_(OriginMat.clone()) {
assert(OriginMat_.type() == CV_8UC3);
}
// 函数的实现
cv::Mat ImageFilter::PrintFilter(const cv::Mat &OriginMat) {
cv::Mat GrayMat;
cv::cvtColor(OriginMat, GrayMat, cv::COLOR_BGR2GRAY);
cv::Mat BinMat;
cv::adaptiveThreshold(GrayMat, BinMat, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY, 11, 9);
cv::Mat OutputMat = GuidedFilter(GrayMat, BinMat, 35, 0.001);
cv::Mat MeanMat;
cv::Mat StdDevMat;
cv::meanStdDev(GrayMat, MeanMat, StdDevMat);
for (int iHeight = 0; iHeight < OutputMat.rows; ++iHeight) {
for (int iWidth = 0; iWidth < OutputMat.cols; ++iWidth) {
cv::Vec<uchar, 1> Color = OutputMat.at< cv::Vec<uchar, 1> >(iHeight, iWidth);
if (Color.val[0] > (MeanMat.at<double>(0, 0) + StdDevMat.at<double>(0, 0))) {
OutputMat.at< cv::Vec<uchar, 1> >(iHeight, iWidth) = cv::min(0xFF, int(Color.val[0] * 1.3));
}
}
}
cv::Mat BlurMat;
cv::GaussianBlur(OutputMat, BlurMat, cv::Size(11, 11), 0);
cv::addWeighted(OutputMat, 0.5 + 1.0, BlurMat, 0.5 - 1.0, 0, OutputMat);
OutputMat = ContrastFilter(OutputMat, 0.2f);
return OutputMat;
}
// 其他的函数实现,略……
}
定义函数的同时可以指定函数的实现:
class Box
{
// 私有的成员函数
double width;
public:
double length; // 长度
double breadth; // 宽度
double height; // 高度
double getVolume(void)
{
return length * breadth * height;
}
};
但是如果在类的外部定义函数,就需要使用范围解析运算符 ::
定义该函数:
double Box::getVolume(void)
{
return length * breadth * height;
}
1.2 类的访问修饰符
1. 类的普通访问权限修饰符
一个类可以有多个 public
、protected
或 private
标记区域。每个标记区域在下一个标记区域开始之前或者在遇到类主体结束右括号之前都是有效的。成员和类的默认访问修饰符是 private
。
三种访问权限修饰符与 Java 中的含义基本是一致的,只是在 C++ 中存在友元,所以在这个方面略有不同:
- private 成员只能被本类成员(类内)和友元访问,不能被派