gpt4 book ai didi

C++:当类构造函数具有多态参数时,为什么 VS2005 将本地实例的直接初始化解释为函数?

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

我在 Visual Studio 2005 中有以下 C++ 代码...

class Base {};
class Derived : public Base {};

class Other {
public:
Other(const Base& obj) {}
void test() {}
};

int _tmain(int argc, _TCHAR* argv[])
{
Other other(Derived());
other.test();
return 0;
}

...编译失败并给出:

test.cpp(19) : error C2228: left of '.test' must have class/struct/union

我通过一些测试确定发生这种情况是因为“other”变量的声明被解释为函数声明(返回 Other 并采用 Derived 参数),而不是 Other 使用单 -参数构造函数。 (VS6 找到构造函数并编译它很好,但它不擅长标准 C++,所以与 VS2005 相比我不信任它)

如果我这样做...

Other other(static_cast<Base&>(Derived()));

... 或使用复制初始化,效果很好。但是它似乎没有看到 Derived() 实例本身是从 Base 派生的,或者它优先考虑函数声明而不是在构造函数参数上尝试多态性。

我的问题是:这是标准的 C++ 行为,还是 VS2005 特定的行为?应该……

Other other(Derived());

...在标准 C++ 中声明一个本地实例,还是应该声明一个函数?

最佳答案

是的,这是标准行为。参见 this C++ FAQ-lite entry .

根据标准,这:

Other other(Derived());

被解释为函数声明,该函数返回 Other 并将另一个函数作为参数返回 Derived 并且没有参数。要解决此问题,您可以使用:

Other other = Other(Derived());

关于C++:当类构造函数具有多态参数时,为什么 VS2005 将本地实例的直接初始化解释为函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2196419/

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