Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

Class method and variable with same name, compile error in C++ not in Java?

class Test {

      bool isVal() const {
          return isVal;
      }

  private:

      bool isVal;
};

On Compiling this file it says

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

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

Although the same would work for java

class Test {

  private boolean isVal;

  public boolean isVal() {
      return isVal;
  }

}

Why does the compile error occur in C++ not in Java?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...