繁体   English   中英

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

[英]How to call method using scope resolution operator

我试图从视觉工作室 .net 框架中了解特定的代码行,根据我的理解,它将属于 class 的方法分配给“firstDigit”变量。 我自己尝试了这个东西。

#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;
}

为什么它不适用于我自己的代码?

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

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

看你对displayThis的定义

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

当你调用sampleClass::sampleInsideClass::displayThis(5)时,你认为this指针指向的 object 是什么? 在您调用displayThis的 memory 中没有 object 。

你可以做两件事,

  • 制作您的 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 . 但问题是,static 函数无法访问任何 class 成员this-> b
  • 创建 object 实例然后调用displayThis

暂无
暂无

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

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