名称查找和类范围 [英] Name Lookup and class scope

查看:72
本文介绍了名称查找和类范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么setVal的返回类型为string类型,而参数类型为double类型

Why is it that the return type of setVal is of type string and the parameter type is of type double

typedef string Type;
Type initVal(); 
class Exercise {
public:
    typedef double Type;
    Type setVal(Type); 
    Type initVal(); 
private:
    int val;
};

Type Exercise::setVal(Type parm) {  
    val = parm + initVal();    
    return val;
}

推荐答案

在命名空间范围内定义成员函数时,C ++为遵循函数的 declarator- id (3.4.1/8).在名称空间范围内查找此类名称之前,先在类范围内查找此类名称.

When member functions are defined in namespace scope C++ provides special name lookup rules for unqualified names that follow the function’s declarator-id (3.4.1/8). Such names are looked up in class scope before they are looked up in namespace scope.

由于普通"成员函数定义中的返回类型位于函数的 declarator-id 中,因此上述特殊规则不适用于它.根据常规"规则进行查找:在名称空间范围内.

Since the return type in an "ordinary" member function definition precedes function’s declarator-id, the aforementioned special rules do not apply to it. It is looked up in accordance with the "usual" rules: in namespace scope.

因此,您的函数定义的返回类型引用::Type,而不是Exercise::Type.它与该类内部所做的任何声明都不匹配.代码格式错误.

For this reason your function definition's return type refers to ::Type, not to Exercise::Type. It does not match any of the declarations made inside the class. The code is ill-formed.

如果您还希望在类范围内查找不合格的返回类型名称,请在函数声明中使用新的 trailing返回类型语法,因为在此语法中,返回类型遵循函数的 declarator-id

If you want the unqualified return type name to be looked up in class scope as well, use the new trailing return type syntax in function declaration, since in this syntax the return type follows function’s declarator-id

auto Exercise::setVal(Type parm) -> Type {  
    val = parm + initVal();    
    return val;
}

这篇关于名称查找和类范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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