调用签名相同但作用域不同的方法
C++ Calling methods with same signature but different scope
我正在做一个使用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
对包含类的访问。
相关文章:
- 未在作用域中声明unordered_map
- 有没有一种方法可以在编译时获得作用域类名
- C++quit()函数中可能存在作用域问题
- 类作用域的类型别名"using":[何时]方法中的用法可以先于类型别名?
- 有没有一种方法可以通过使用指针来处理作用域
- 将对象的属性传递到方法时出现作用域问题.(opencv相关)
- 在类作用域内不能将“static_assert”与“sizeof”一起使用(但方法作用域可以)
- 为什么 noexcept 说明符的作用域不在声明的方法内?
- 有没有一种方法可以为本地作用域中的单例分配名称
- 当我把一个方法作为参数传递时,我怎么能忽略作用域呢
- 线程静态类方法与全局作用域
- 从类方法返回作用域枚举时,命名空间混淆
- 类方法中创建变量的作用域
- 当方法抛出异常时,方法作用域的对象将被销毁
- 将.txt文件中的字符串输出到成员方法局部作用域之外的动态数组
- 调用签名相同但作用域不同的方法
- 未在此作用域中声明的信号/对class::方法的未定义引用
- 在类作用域内定义方法时,除非在原始 cpp 文件中的其他位置调用方法,否则项目不会编译
- 条件运算符是在全局作用域中初始化全局变量的唯一方法
- 为什么在方法作用域结束后要更改向量内容