【问题标题】:C++ : how to define a Class just with static functions [closed]C ++:如何仅使用静态函数定义类[关闭]
【发布时间】:2012-10-13 10:16:02
【问题描述】:

我想创建一个 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;
}

这是我收到的错误。

谁能指出我做错了什么?我错过了什么?

【问题讨论】:

  • 为什么不也复制错误,没有要编译的标头
  • 你忘了再次复制错误..

标签: c++ opencv static-methods


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    认为你在类减速之后缺少一个分号。试试吧,

    class Utils
    {
    public:
        static void drawPoint(Mat &img, int R, int G, int B, int x, int y);
    }; // <- Notice the added semicolon
    

    【讨论】:

      【解决方案3】:

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

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

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

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

      要更深入地讨论静态类成员函数与命名空间范围函数的优缺点,请参阅:Namespace + functions versus static methods on a class

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-06
        • 2011-11-05
        • 2020-01-27
        • 2022-12-18
        相关资源
        最近更新 更多