gpt4 book ai didi

c++ - 常量/非常量重载解析的问题

转载 作者:可可西里 更新时间:2023-11-01 15:09:31 28 4
gpt4 key购买 nike

我有一个看起来像这样的类:

class ClassA
{
public:
float Get(int num) const;
protected:
float& Get(int num);
}

在类之外,我调用了 Get() 函数。

float foo = classAInstance.Get(i);

我希望这会调用公共(public)版本,但 Visual Studio 会出错:

error C2248: 'ClassA::Get' : cannot access protected member declared in class 'ClassA'

当注释掉 protected 重载并删除对它的所有引用时,代码会编译。

为什么编译器在可访问的成员可用时尝试使用不可访问的成员?是否有一种可接受的方法来强制编译器选择正确的重载?有没有引用成员函数的解析规则?

最佳答案

的确,重载决议发生在可访问性检查之前。标准的第 13.3 节 ([over.match]) 说:

Overload resolution is a mechanism for selecting the best function to call given a list of expressions that are to be the arguments of the call and a set of candidate functions that can be called based on the context of the call. The selection criteria for the best function are the number of arguments, how well the arguments match the parameter-type-list of the candidate function, how well (for non-static member functions) the object matches the implicit object parameter, and certain other properties of the candidate function. [ Note: The function selected by overload resolution is not guaranteed to be appropriate for the context. Other restrictions, such as the accessibility of the function, can make its use in the calling context ill-formed. — end note ]

通常的解决方法是为公共(public)函数和 protected 函数指定不同的名称。


注意,这有时很有用,例如:

class Blah
{
const std::string& name_ref;

Blah(const char*) = delete;

public:
Blah(const std::string& name) : name_ref(name) {}

void do_something_with_name_ref() const;
};

std::string s = "Blam";
Blah b(s); // ok

请注意,name_ref 只会被读取,因此将其设为const 是合适的。但是,const 引用可以绑定(bind)到临时对象,将 name_ref 绑定(bind)到临时对象将是一个悬空引用,导致 do_something_with_name_ref() 中出现未定义的行为.

Blah c("Kablooey!"); // would be undefined behavior
// the constructor overload makes this a compile error

私有(private)构造函数重载防止临时 std::string 被隐式构造和绑定(bind)。

关于c++ - 常量/非常量重载解析的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6239630/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com