【问题标题】:Why do I get the error "no matching function for call to A::A(A)" on Linux but not on Windows为什么我在 Linux 上但在 Windows 上却没有出现错误“没有调用 A::A(A) 的匹配函数”
【发布时间】:2014-11-17 06:16:55
【问题描述】:

当我使用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 上的代码有什么问题?

【问题讨论】:

  • 请注意,您的减法运算符也应该采用常量引用,除非您的实际实现可以修改其中一个输入参数(但实现可能一开始不应该这样做)。

标签: c++ linux compiler-errors


【解决方案1】:

在线

A a3 = a1 - a2;

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

A(A& a) { ... }

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

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

根据 Brian 的说法,至于 Visual C++ 接受这一点的原因,这似乎是为了向后兼容而保留的语言扩展。见similarquestions

【讨论】:

  • Visual Studio 允许非常量左值引用绑定到右值。这是一个长期存在的偏离标准的点,微软不会修复它,因为它会破坏太多代码。
猜你喜欢
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
相关资源
最近更新 更多