类方法和变量具有相同的名称,编译错误在C ++不是在Java? [英] Class method and variable with same name, compile error in C++ not in Java?

查看:160
本文介绍了类方法和变量具有相同的名称,编译错误在C ++不是在Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Test {

      bool isVal() const {
          return isVal;
      }

  private:

      bool isVal;
};

在编译此文件时,会显示

On Compiling this file it says


testClass.cpp:9:声明`bool
Test :: isVal'

testClass.cpp:9: declaration of `bool Test::isVal'

testClass.cpp:3: b $ b前声明`bool
Test :: isVal()'

testClass.cpp:3: conflicts with previous declaration `bool Test::isVal()'

p>

Although the same would work for java

class Test {

  private boolean isVal;

  public boolean isVal() {
      return isVal;
  }

}

不知道为什么C ++无法处理。

Not sure why C++ cannot handle this.

推荐答案

因为C ++不是Java。您可以输入会员的地址:

Because C++ is not Java. You can take the address of a member:

&Test::isVal

所以你不能有两个成员有相同的名字,除了你可以重载成员函数。即使你可以通过某种方式消除歧义,下一个问题已经出现在其他地方。

So you can't have two members have the same name, except that you can overload member functions. Even if you could disambiguate that by some kind of cast, the next problem would already arise at other places.

在C ++中,很多人包括我通常会特别调用数据成员,例如在他们的名字前加上 m 。这避免了问题:

In C++, a lot of people including me usually call data members specially, like putting a m before their name. This avoids the problem:

class Test {
public:
    bool IsVal() const { return mIsVal; }
private:
    bool mIsVal;
};

这篇关于类方法和变量具有相同的名称,编译错误在C ++不是在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆