gpt4 book ai didi

c++ - [dcl.fct.default]/10 中的明显矛盾

转载 作者:搜寻专家 更新时间:2023-10-31 00:54:47 25 4
gpt4 key购买 nike

[dcl.fct.default]/10 :

A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides. [ Example:

struct A {
virtual void f(int a = 7);
};
struct B : public A {
void f(int a);
};
void m() {
B* pb = new B;
A* pa = pb;
pa->f(); // OK, calls pa->B::f(7)
pb->f(); // error: wrong number of arguments for B::f()
}

—end example ]

除了我在上面强调的陈述外,这段话和例子对我来说都很清楚。当我读到这篇文章时,我的印象是它与该段的第一部分相矛盾,即虚函数调用在虚函数声明中使用由静态类型决定的默认参数指示对象的指针或引用。

最佳答案

它们并不矛盾,因为它们指的是不同的事物。

A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object.

这意味着:

#include <iostream>

struct Base
{
virtual void foo(int x = 3) { std::cerr << x << '\n'; }
};

struct Derived : Base
{
virtual void foo(int x = 4) { std::cerr << x << '\n'; }
};

int main()
{
Derived d;
Base* ptr = &d;
ptr->foo(); // prints 3, not 4
}

( live demo )

An overriding function in a derived class does not acquire default arguments from the function it overrides.

另一方面,这意味着以下内容:

#include <iostream>

struct Base
{
virtual void foo(int x = 3) { std::cerr << x << '\n'; }
};

struct Derived : Base
{
virtual void foo(int x) { std::cerr << x << '\n'; }
};

int main()
{
Derived d;
d.foo(); // doesn't compile; missing value for x
}

( live demo )

I get the impression that it contradicts the first part of the paragraph, i.e. that a virtual function call uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object.

没有。这意味着如果您通过其 Base 接口(interface)访问该对象,您将获得 Base 的默认参数……并且如果您通过其 Derived 接口(interface)访问该对象,而 Derived 没有默认参数自己的,你不会得到基地的。同一枚硬币的两个截然不同的面。

而且,公平地说,引用的标准文本给出了完全相同的示例。

关于c++ - [dcl.fct.default]/10 中的明显矛盾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44122476/

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