gpt4 book ai didi

c++ - 使用 Visual Studio 2008 编译但不使用 g++ 的引用相关问题

转载 作者:行者123 更新时间:2023-11-30 01:26:43 25 4
gpt4 key购买 nike

以下代码可以用 Visual Studio 2008 编译,但不能用 Mac OSX 上的 g++ 编译:

class A
{
public:
A CreateA()
{
A a;
return a;
}
};

class B
{
public:
void ComputeWithA
(
A &a // Here, removing the reference solves the problem
)
{
return;
}
};

int main ()
{
A a;
B b;

b.ComputeWithA(a); // Works
b.ComputeWithA(a.CreateA()); // Invalid arguments 'Candidates are: void ComputeWithA(A &)'

return 0;
}

为什么这个引用相关的问题?任何解释将不胜感激。

最好的问候。

最佳答案

a.CreateA() 为您提供 R 值(即临时值)。 ComputeWithA 需要一个引用,也就是 L 值。该标准规定您不能将 R- 转换为 L-值,因此 MSVC 在这里是错误的。

但是,您可以使用 const 引用,因为这种情况是明确允许的:

void ComputeWithA(A const &a) // add a const and everything works fine

关于c++ - 使用 Visual Studio 2008 编译但不使用 g++ 的引用相关问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9791612/

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