简体   繁体   中英

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. 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

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? There is no object in memory on which you are calling displayThis .

You can do two things,

  • Make your 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 . But the catch is, static functions cannot access any class members this-> b .
  • Create and object instance and then call displayThis

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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