繁体   English   中英

如何const声明this指针作为参数发送

[英]How to const declare the this pointer sent as parameter

我想常量声明接收此指针作为参数。

static void Class::func(const OtherClass *otherClass) 
{ 
   // use otherClass pointer to read, but not write to it.
}

它被这样称呼:

void OtherClass::func()
{
  Class::func(this);
}

如果我不const声明OtherClass指针,则不会编译,我可以更改它。

谢谢。

您不能像这样定义静态类memberv函数:

static void Class::func(const OtherClass *otherClass) 
{ 
   // use otherClass pointer to read, but not write to it.
}

必须在类声明中将函数声明为静态,然后函数定义如下所示:

void Class::func(const OtherClass *otherClass) 
{ 
   // use otherClass pointer to read, but not write to it.
}

如果不更改指针或指向的对象,为什么不采用const引用呢?

void Class::func(const OtherClass& otherClass) 
{ 
   // use otherClass ref for read-only use of OtherClass
}
void OtherClass::func()
{
  Class::func(*this);
}

这在我的机器上编译正常:

#include <iostream>

class bar;

class foo {
public:
    static void f(const bar* b) { std::cout << b << '\n'; }
};

class bar {
public:
    void f() {foo::f(this);}
};

int main(void)
{
    bar b;
    b.f();
    return 0;
}

那么您做了什么不同的事情?

处理const和指针时,诀窍是从右到左读取。 查看http://www.parashift.com/c++-faq-lite/const-correctness.html以获得良好的概述。

暂无
暂无

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

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