在C++中声明类的函数内部变量

rid*_*ctg 8 c++ variables class

MyFill是一个类,MyFill2该类中的一个函数.

在类的公共函数内声明变量(thickness和lineType) - >之间的区别是什么

MyFill::MyFill (Mat img, Point center)
{
    MyFill2 (img, center);
}

void MyFill::MyFill2(Mat img, Point center)
{
    int thickness = -1;
    int lineType = 8;
    circle (
        img,
        center,
        w/32,
        Scalar( 0, 0, 255 ),
        thickness,
        lineType
    );
}
Run Code Online (Sandbox Code Playgroud)

...并且只是在私有标签(私有:)中声明它们,就像在头文件中一样 - >

class MyFill {
public:
    MyFill(Mat img1, Point center1);
    void MyFill2 (Mat img, Point center);
private:
    int thickness = -1;
    int lineType = 8;
};
Run Code Online (Sandbox Code Playgroud)

第一个正常.但第二个没有.如果我想选择第二种选择,我需要做什么?正确的代码和一些解释可能有所帮助.

Jos*_*Pla 5

不允许将值赋给类范围内的变量,只能在函数内部或全局范围内执行此操作.

class MyFill {
public:
MyFill(Mat img1, Point center1);
void MyFill2 (Mat img, Point center);
private:
int thickness;
int lineType;
};
Run Code Online (Sandbox Code Playgroud)

您的标题需要更改为上述内容.然后在任何你喜欢的函数中设置你的值,最好像你的构造函数那样:

MyFill::MyFill(Mat img1, Point center1)
{
     thickness = -1;
     lineType = 8;
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 在评论中提出您的问题:

函数参数中变量名的标识符不需要在声明和定义之间匹配,只需要匹配类型及其顺序.它使它更清晰,但不是必需的.

功能原型实际上只被视为以下内容:

void MyFill2(Mat, Point);
Run Code Online (Sandbox Code Playgroud)

当你给它一个定义时,那就是标识符的分配真的很重要:

void MyFill2(Mat m, Point p)
{
    //....
}
Run Code Online (Sandbox Code Playgroud)