【问题标题】:C++ static method needed需要 C++ 静态方法
【发布时间】:2013-04-09 12:26:52
【问题描述】:

我有一个方法run()MyClass 的成员。在编译时,我得到

    Error   3   error C2662: 'MyClass::run' : 
    cannot convert 'this' pointer from 'const MyClass' to 'MyClass&'

ITOH,如果我把这个方法设为静态,我没有错误。方法调用发生在这里:

Errors MyClass::execute( const AbstractExecutionContext &ctx ) const
{
    Errors errs;

    Watch wat; wat.restart();
    {

        run() ;

    }

    return errs;
}

这个方法的声明是

Errors execute(const AbstractExecutionContext &ctx) const;

我希望我可以让这个方法不是静态的,因为如果它是静态的,那么 run() 调用的方法也必须是静态的,并且不能访问非静态的数据成员(我必须丑陋地将它们作为参数传递到方法)。

编译错误的原因是什么,有什么解决办法?

【问题讨论】:

  • 是否可以添加完整代码?或者至少是类定义?
  • 此链接可能会有所帮助:stackoverflow.com/questions/5008541/…
  • 您使用的是this.something,而不是this->something。但错误似乎在MyClass::run() 而不是MyClass::execute()
  • 静态方法在哪里?
  • run() 不是静态的 --> 我得到错误。 run() 是静态的 --> 没有错误

标签: c++ static constants static-methods


【解决方案1】:

run 也必须是 const。或函数execute 不应为const

在你的执行函数中thisconst MyClass* const this。当run 不是static 而不是const 时 - 尝试调用const 对象的non-const 函数。如果 run 是静态的 - 一切正常,因为 static 函数没有 this 指针。

【讨论】:

  • 静态方法没有 this 指针,没有对象状态可以保持不变。
  • 可以说我的解决方案是让 run() 调用的所有方法都是静态的,并且我也让我需要的所有数据成员都是静态的。那么是否可以在运行时更改此数据成员的值?
  • @antitrust 是的,但是静态成员的所有者是 CLASS,而不是 OBJECT。
  • 是否可以随时使用 MyClass::member = val 更改静态成员的值; ?
  • 将数据成员作为所有静态方法的参数传递是否更合适
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
相关资源
最近更新 更多