-2

我想创建一个 C++ 类,它只包含我无论如何都可以使用的静态函数。我已经创建了一个.h带有声明的.cpp文件和一个带有定义的文件。但是,当我在我的代码中使用它时,我会收到一些奇怪的错误消息,我不知道如何解决。

这是我的Utils.h文件的内容:

#include <iostream>
#include <fstream>
#include <sstream>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

#include <vector>
#include <opencv/cv.h>
#include <opencv/cxcore.h>

class Utils
{
public:
    static void drawPoint(Mat &img, int R, int G, int B, int x, int y);
};

这是我的Utils.cpp文件的内容:

#include "Utils.h"

void Utils::drawPoint(Mat &img, int R, int G, int B, int x, int y)
{
img.at<Vec3b>(x, y)[0] = R;
img.at<Vec3b>(x, y)[1] = G;
img.at<Vec3b>(x, y)[2] = B;
}

这就是我想在我的main函数中使用它的方式:

#include <iostream>
#include <fstream>
#include <sstream>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

#include <vector>
#include <opencv/cv.h>
#include <opencv/cxcore.h>

#include "CThinPlateSpline.h"
#include "Utils.h"

int main()
{
Mat img = imread("D:\\image.png");
if (img.empty()) 
{
    cout << "Cannot load image!" << endl;
    system("PAUSE");
    return -1;
}
Utils.drawPoint(img, 0, 255, 0, 20, 20);
imshow("Original Image", img);
waitKey(0);
return 0;
}

这是我收到的错误。

有人可以指出我做错了什么吗?我错过了什么?

4

3 回答 3

5
Utils::drawPoint(img, 0, 255, 0, 20, 20);
     ^^ (not period)

是你如何调用一个静态函数。该时间段用于成员访问(即当您拥有实例时)。

为了完整起见:

Utils utils; << create an instance
utils.drawPoint(img, 0, 255, 0, 20, 20);
     ^ OK here
于 2012-10-13T10:19:56.707 回答
1

认为您在课程减速后缺少分号。尝试,

class Utils
{
public:
    static void drawPoint(Mat &img, int R, int G, int B, int x, int y);
}; // <- Notice the added semicolon
于 2012-10-13T10:17:47.253 回答
0

这不是您问题的直接答案,但使用命名空间范围的函数可能更适合您的需求。我的意思是:

namespace Utils
{
    void drawPoint(Mat &img, int R, int G, int B, int x, int y);
}

::语义保持不变,但现在:

  • 你不能实例化一个Utils对象,这对于“静态类”来说是没有意义的
  • 您可以using Utils用来避免Utils::选择(和有限)范围内的前缀

有关静态类成员函数与命名空间范围函数的优缺点的更深入讨论,请参阅:命名空间 + 函数与类上的静态方法

于 2012-10-13T10:42:43.197 回答