英文:
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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论