调用签名相同但作用域不同的方法

C++ Calling methods with same signature but different scope

本文关键字:方法 作用域 调用      更新时间:2023-10-16

我正在做一个使用TinyXML2的项目。我试图调用方法 xmlatattribute * findatattribute (const char* name)

这个方法被实现定义为:

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

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

如何调用公共方法,方法原型末尾的const部分做什么?

函数可以仅根据它们的const属性进行重载。这是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

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

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

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

public方法适用于const对包含类的访问。