【问题标题】:C++ Calling methods with same signature but different scope [duplicate]C ++调用具有相同签名但范围不同的方法[重复]
【发布时间】:2014-08-31 10:55:25
【问题描述】:

我正在使用 TinyXML2 开发一个项目。我正在尝试调用方法 XMLAttribute* FindAttribute(const char* name)

该方法由实现定义为:

public : 
const XMLAttribute* FindAttribute( const char* name ) const;

private :
XMLAttribute* FindAttribute( const char* name );

我有点困惑,一个方法如何在公共和私有范围内具有相同的签名。我只能猜测它没有,尽管我并不真正理解公共定义末尾的 const 部分。但是,我需要调用公共方法,但 g++ sais "tinyxml2::XMLElement::FindAttribute(const char*) 是私有的"

如何调用public方法,方法原型末尾的const部分有什么作用?

【问题讨论】:

  • 是的,这与尾随的const有关,而不是public/private。如果您想象传递给这些函数的隐式this*,它就像两个函数foo(T *this)foo(T const *this)

标签: c++ tinyxml


【解决方案1】:

函数可以仅根据它们的constness 重载。这是 C++ 的一个重要特性。

// const member function:
const XMLAttribute* FindAttribute( const char* name ) const;

// non-const member function
XMLAttribute* FindAttribute( const char* name );

在这种情况下,使函数不同的const 是括号后面的const。括号前的const 不属于方法签名,而括号后面的const 则属于。后者对const 的使用指定了哪些成员函数可以从const 对象中调用,哪些不可以。换句话说,它指定了const 对象的契约。

如果你有一个const 对象,const 方法将被调用:

const MyObject cObj;
cObj.FindAttribute("cats");
// const method will be called

如果你有一个非const 的对象,编译器会寻找一个非const 的方法并调用它。如果它不存在,它将寻找const 方法并调用它。编译器之所以这样工作,是因为从非const 对象调用const 成员函数是合法的,但从const 对象调用非const 成员函数是非法的。

MyObject obj;
obj.FindAttribute("cats");
// non-const method will be called
// if it does not exist the compiler will look for a const version

【讨论】:

  • +1 示例和详细说明编译器如何解析为可用的公共方法。
【解决方案2】:

我有点困惑,一个方法如何在公共和私有范围内具有相同的签名。

他们实际上没有相同的签名

const XMLAttribute* FindAttribute( const char* name ) const;
                                                   // ^^^^^^

public 方法适用于const 对包含类的访问。这对函数签名的唯一性很重要。

【讨论】:

    猜你喜欢
    • 2013-02-28
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多