很抱歉不确定之前是否曾经问过,我真的不知道该怎么查.我是Java的C++新手.当我们想要用Java调用对象上的函数时,我们说picture.rotateRight();
然后,在rotateRight(),我们有类似的东西int height=this.getHeight();.但是,我们如何在C++中执行此操作?我有一个名为的方法invertcolors();然后我有类似的东西:
Image* myImage = new Image();
bool b = myImage->ReadFromFile("in_01.bmp");
myImage->invertcolors();
void invertcolors(){
int width=TellWidth();
int height=TellHeight();
...
}
Run Code Online (Sandbox Code Playgroud)
如何myImage在不实际说明的情况下从方法定义进行访问myImage(因为以后可以更改该名称).
此外,功能参数是不可协商的.
首先,您的invertcolors()函数定义是非成员函数.虽然您已在Image类中声明它,但您没有以任何方式将实现链接到类,因此编译器认为它是非成员函数.要使其成为成员Image,您需要使用Image::invertcolors如下:
void Image::invertcolors(){
int width=TellWidth();
int height=TellHeight();
...
}
Run Code Online (Sandbox Code Playgroud)
你确实得到this了C++,但它是一个指针,所以你必须this->getHeight()在C++中使用它.但请注意,在这种情况下它是多余的.作为初学者,您可能会在具有相同参数名称的方法中找到唯一真正的用途.在这种情况下,您需要使用this->height = height例如.但请注意,C++在这里添加了很好的语法.此代码与简单的setter相同:
void Image::setHeight(int height): height(height) {}
Run Code Online (Sandbox Code Playgroud)
请注意,Java和C++都不this是运算符..,->和+是运营商的例子.