不同范围的函数重载的可见性

huangapple go评论68阅读模式
英文:

Visibility of function overloads with different scope

问题

下面的代码出错:error: ‘double& Sample::GetValue()’在此上下文中是受保护的 | double v = ms.GetValue();。如果删除受保护的函数,则可以编译通过。这是编译器的错误吗,不能选择具有不同范围的正确函数重载?

英文:

The code below gives error: error: ‘double& Sample::GetValue()’ is protected within this context | double v = ms.GetValue();. If the protected function if deleted it compiles fine. Is it the bug of the compiler that cannot select the correct function overload with different scope?

class Sample
{
public:
    Sample() {}
    virtual ~Sample() {}
    const double& GetValue() const {return v;}
    void Print() {std::cout << v << std::endl;}
protected:
    double& GetValue() {return v;}
private:
    double v;
};

class Sample2
{
public:
    Sample2() {}

    void Compute()
    {
        double v = ms.GetValue();
    }

private:
    Sample ms;
};

答案1

得分: 3

函数的可见性不会改变重载解析规则。这里没有错误,double& GetValue()只是比const double& GetValue() const更合适的候选项。

英文:

Visibility of a function doesn't alter overload resolution rules. There is no error here, double& GetValue() is simply a better candidate than const double& GetValue() const

答案2

得分: 1

梦之风说的是,但编译器不知道你想调用 const double& GetValue() const(顺便说一下,应该是 double GetValue() const),因为 ms 没有声明为 const

不过有一个简单的解决办法:

void Compute()
{
    const Sample &const_ms = ms;
    double v = const_ms.GetValue();
}

在线演示

英文:

What The Dreams Wind said, but the compiler doesn't know you want to call const double& GetValue() const (which should be double GetValue() const, btw) because ms is not declared const.

There's an easy fix though:

void Compute()
{
    const Sample &const_ms = ms;
    double v = const_ms.GetValue();
}

Live demo

huangapple
  • 本文由 发表于 2023年3月7日 01:41:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定