C++ 多拷贝赋值运算符

标签 c++ operator-overloading language-lawyer assignment-operator

我正在学习 C++,我有一个关于赋值运算符的问题。
基于这里写的内容 https://en.cppreference.com/w/cpp/language/copy_assignment , 看起来

...a class can have multiple copy assignment operators, e.g. both T& T::operator=(const T &) and T& T::operator=(T).


我试图用两个运算符创建一个类,但我看不出我错在哪里,因为我从编译器中得到了这个:

error C2593: 'operator =' ambiguous*


这是类(class):
class Point2D
{
public:
    Point2D(); // default constructor
    Point2D(double xValue, double yValue); // overloaded constructor
    Point2D(const Point2D& ref); // copy constructor const
    Point2D(Point2D& ref); // copy constructor for copy and swap
    Point2D(Point2D&& moveRef); // move constructor

    ~Point2D(); // destructor

    Point2D& operator=( const Point2D& other ); // copy assignment operator const
    Point2D& operator=( Point2D other ); // copy assignment operator for copyAndSwap
private:
    double x;
    double y;

    int *ptr;
};
这是它给我错误的地方:
void copy_assign_test()
{
    cout << endl << "Copy assign" << endl;

    Point2D a(1, 1);
    Point2D b(2, 2);
    
    Point2D c(3, 3);
    Point2D& ptRef = c;
    Point2D d(6, 6);

    a = ptRef; // error: ambiguous operator
    b = a; // // error: ambiguous operator
    d = Point2D(7,7); // error: ambiguous operator
}
我的问题涉及以下几点:
  • 为什么是 a=ptRef歧义如果 ptRef是引用吗?
  • 为什么是 b=a如果 a 不明确没有声明为引用?
  • 为什么是 d = Point2D(7,7)歧义如果 Point2D(7,7)不是引用吗?

  • 我所有的测试都是使用 Visual Studio 2019 编译的,符合 C++17 标准。

    最佳答案

    您引用的文档源自 C++ 标准 [class.copy] 的声明。 (C++14)/ [class.copy.assign] (C++17)部分:

    15.8.2 Copy/move assignment operator

    1. A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X,X&,const X&,volatile X& or const volatile X&.121[Note: An overloaded assignment operator must be declared to have only one parameter; see 16.5.3.— end note] [Note:More than one form of copy assignment operator may be declared for a class.— end note]

    (强调)
    因此,您引用的文档是正确的,尽管它指的是标准中的注释。 [编辑:剪断]
    如果标准允许它为什么不编译?
    在说明允许哪些参数和允许重载之后,标准不必还说明哪些组合是(无效)有效的,因为这意味着重复。在冗长的 [over.match] 中概述了重载解决规则(以及由此产生的歧义和冲突规则)。第 16.3 节,共 20 页。

    关于C++ 多拷贝赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63826319/

    相关文章:

    c++ - 为什么在同一个作用域中声明多个相同的名称会导致程序格式错误?

    c++ - 移动内容后调用 vector.resize(0) 是否安全

    c++ - C++20 模板ambas 的限制和使用

    C++ 提取器 (>>) 重载不读取和分配 Matrix 类

    c++ - 如果我们删除 [-Wreturn-local-addr] 可以吗(警告 : address of local variable returned) by using static keyword in c++?

    c++ - 如何在 OpenGL 中渲染非平凡粒子

    c++ - Vector 不创建多个类对象

    c++ - 在 C++ 中重载间接运算符

    c++ - Microsoft 重载 << 运算符示例会引发链接错误

    c++ - OpenCV SURF 功能未实现