简体   繁体   English

如何使用 scope 分辨率运算符调用方法

[英]How to call method using scope resolution operator

I'm trying to understand a specific line of code from visual studio .net framework, based on what i understand, it is assigning the method that belongs to the class double into the 'firstDigit' variable.我试图从视觉工作室 .net 框架中了解特定的代码行,根据我的理解,它将属于 class 的方法分配给“firstDigit”变量。 I tried this thing out on my own.我自己尝试了这个东西。

#include <iostream>
class sampleClass {
    int a;
    public:

    class sampleInsideClass {
        public:
        int b;
    
        int displayThis (int a){
        this->b = a;
        return (this->b);
        }
    };
};

int main() {

   sampleClass::sampleInsideClass obj;
   std::cout << sampleClass::sampleInsideClass::displayThis(5); //this is producing error: cannot call member function 'int sampleClass::sampleInsideClass::displayThis(int)' without object

return 0;
}

why doesn't it work on my own code?为什么它不适用于我自己的代码?

//-----this is the code from visual studio---------------------------//

//variable = class::method();
firstDigit = Double::Parse(txtDisplay->Text);

Look at your definition of displayThis看你对displayThis的定义

int displayThis (int a){
    this->b = a;
    return (this->b);
}

When you call sampleClass::sampleInsideClass::displayThis(5) , what do you think the object pointed by this pointer is?当你调用sampleClass::sampleInsideClass::displayThis(5)时,你认为this指针指向的 object 是什么? There is no object in memory on which you are calling displayThis .在您调用displayThis的 memory 中没有 object 。

You can do two things,你可以做两件事,

  • Make your function static.制作您的 function static。 A static function is a member function of a class that can be called even when an object of the class is not initialized, like Double::Parse . A static function is a member function of a class that can be called even when an object of the class is not initialized, like Double::Parse . But the catch is, static functions cannot access any class members this-> b .但问题是,static 函数无法访问任何 class 成员this-> b
  • Create and object instance and then call displayThis创建 object 实例然后调用displayThis

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM