gpt4 book ai didi

c++ - 为什么在 Linux 上出现错误 "no matching function for call to A::A(A)"而在 Windows 上却没有

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:31 25 4
gpt4 key购买 nike

当我使用 g++ test.cpp 编译时,以下代码在 Linux 上引发错误:

#include <iostream>

using namespace std;

class A
{
public:
A(){
cout << "call A()" << endl;
};
A& operator = (const A& a) {
cout << "call operator =" << endl;
return *this;
}
A(A& a) {
cout << "call A(A& a)" << endl;
}
};

A operator - (A& a1, A& a2)
{
cout << "call operate -" << endl;
return a1;
}

int main()
{
A a1;
A a2;
A a3 = a1 - a2;
//a1 = a2;
return 0;
}

错误是:

test.cpp: In function ‘int main()’:
test.cpp:30: error: no matching function for call to ‘A::A(A)’
test.cpp:15: note: candidates are: A::A(A&)
test.cpp:8: note: A::A()

但在使用 Visual Studio 2010 编译时,它可以在 Windows 上运行。为什么?我在 Linux 上的代码有什么问题?

最佳答案

在线

A a3 = a1 - a2;

在这里,您减去了 a1a2,得到了一个临时值(技术上是 prvalue)。但是,您的复制构造函数需要一个非常量左值引用:

A(A& a) { ... }

C++ 标准不允许这样做:纯右值不能绑定(bind)到非常量左值引用。您应该在复制构造函数中使用 const 引用参数:

A(const A& a) { ... }

至于为什么它被 Visual C++ 接受,据 Brian 说,这似乎是为了向后兼容而保留的语言扩展。参见 similar questions .

关于c++ - 为什么在 Linux 上出现错误 "no matching function for call to A::A(A)"而在 Windows 上却没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26966660/

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