【问题标题】:Calling an operator function in a class in C++在 C++ 中调用类中的运算符函数
【发布时间】:2020-05-12 01:37:48
【问题描述】:

学习C++,在一个类中得到一个操作符函数却不知道怎么调用:

class Getbytes
{
public:
      Getbytes();

      int operator() (unsigned char* C1, unsigned char* C2)
       {do something to C1 and C2 and return int; };
}

main ()
{

 Getbyes myBytes;

//Here, how to call the "operator() (unsigned char* C1, unsigned char*C2)"?
 myBytes??  

}

【问题讨论】:

  • 函数调用运算符使对象可作为函数调用,因此您只需像任何其他函数一样“调用”该对象。
  • 您的 main 缺少返回类型。 main必须用返回类型声明,返回类型必须int。在类定义的结束 } 之后,您还缺少一个分号。另一方面,分号不属于函数定义之后。所以operator()重载的关闭}之后的;不属于那里。

标签: c++ function class operator-keyword


【解决方案1】:

如果您想详细一点,可以将其称为 myBytes();myBytes.operator();

当然,您还需要传递函数所需的参数。赞myBytes("foo", "bar");

【讨论】:

    【解决方案2】:

    你可以这样称呼它

    Getbytes myBytes;
    
    unsigned char s1[] = "Hello";
    unsigned char s2[] = "World";
    
    myBytes( s1, s2 );
    

    myBytes.operator()( s1, s2 );
    

    如果操作符不改变Getbytes类的对象本身,那么它应该被声明为

    int operator() (unsigned char* C1, unsigned char* C2) const;
    

    【讨论】:

      猜你喜欢
      • 2011-02-23
      • 2011-01-27
      • 2015-11-02
      • 2023-03-17
      • 1970-01-01
      • 2022-03-22
      • 2013-02-06
      • 2011-05-02
      • 2016-11-21
      相关资源
      最近更新 更多