名称查找和 class 范围

Name Lookup and class scope

为什么setVal的return类型是string类型,参数类型是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;
}

因为局部变量会自动覆盖全局变量。

该代码无法编译,我无法梳理它应该做什么,但我认为您问题的答案是参数的类型为 Exercise::Type,而 return 值是 ::Type 类型,全局 typedef。如果你想让它们匹配,当你在 class 定义之外定义 setVal 时,你需要将 return 值完全指定为 Exercise::Type,如:

typedef string Type;

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

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

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

由于 return 键入 "ordinary" 成员函数定义 先于 函数的 declarator-id,前述特殊规则不适用。它是根据 "usual" 规则查找的:在命名空间范围内。

因此,您的函数定义的 return 类型指的是 ::Type,而不是 Exercise::Type。它与 class 中的任何声明都不匹配。代码格式错误。

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

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