在 C++ 中,具有 const 数据成员的类可以没有复制赋值运算符吗?

Dim*_*tic 4 c++ copy-assignment

我正在设计一个类,它应该有一个名为K. 我也希望这个类有一个复制赋值运算符,但编译器似乎从任何具有 const 数据成员的类中隐式删除了复制赋值运算符。这段代码说明了基本问题:

class A
{
    private:
       const int K;
    public:
       A(int k) : K(k) {} // constructor
       A() = delete; // delete default constructor, since we have to set K at initialization

       A & operator=(A const & in) { K = in.K; } // copy assignment operator that generates the error below
}
Run Code Online (Sandbox Code Playgroud)

这是它生成的错误:

constructor.cpp:13:35: error: cannot assign to non-static data member 'K' with const- 
qualified type 'const int'
            A & operator=(A const & in) { K = in.K; }
                                          ~ ^
constructor.cpp:6:13: note: non-static data member 'K' declared const here
            const int K;
            ~~~~~~~~~~^
1 error generated.
Run Code Online (Sandbox Code Playgroud)

我想我明白编译器为什么要这样做;我想要复制到的类的实例必须存在才能复制到,K如果它是常量,我不能在该目标实例中分配给,正如我在上面尝试做的那样。

我对这个问题的理解正确吗?如果是这样,有没有办法解决这个问题?也就是说,我可以为我的类定义一个复制构造函数并仍然提供K类似 const 的保护吗?

Joh*_*eau 5

在 C++ 中,具有const数据成员的类可能具有复制构造函数。

#include <iostream>

class A
{
private:
    const int k_;
public:
    A(int k) : k_(k) {}
    A() = delete;
    A(const A& other) : k_(other.k_) {}

    int get_k() const { return k_; }
};

int main(int argc, char** argv)
{
    A a1(5);
    A a2(a1);

    std::cout << "a1.k_ = " << a1.get_k() << "\n";
    std::cout << "a2.k_ = " << a2.get_k() << "\n";
}
Run Code Online (Sandbox Code Playgroud)

输出:

a1.k_ = 5
a2.k_ = 5
Run Code Online (Sandbox Code Playgroud)

在 C++ 中,具有const数据成员的类不能使用默认赋值运算符。

class A
{
private:
    const int k_;
public:
    A(int k) : k_(k) {}
    A() = delete;
    A(const A& other) : k_(other.k_) {}

    int get_k() const { return k_; }
};

int main(int argc, char** argv)
{
    A a1(5);
    A a2(0);

    a2 = a1;
}
Run Code Online (Sandbox Code Playgroud)

产生编译时错误:

const_copy_constructor.cpp: In function ‘int main(int, char**)’:
const_copy_constructor.cpp:18:10: error: use of deleted function ‘A& A::operator=(const A&)’
   18 |     a2 = a1;
      |          ^~
const_copy_constructor.cpp:1:7: note: ‘A& A::operator=(const A&)’ is implicitly deleted because the default definition would be ill-formed:
    1 | class A
      |       ^
const_copy_constructor.cpp:1:7: error: non-static const member ‘const int A::k_’, can’t use default assignment operator
Run Code Online (Sandbox Code Playgroud)

在 C++ 中,const只要您不尝试更改const数据成员,具有数据成员的类就可以使用非默认赋值运算符,但是如果以下情况之一,您最好仔细考虑使用此赋值运算符的含义基础成员不能修改。

class A
{
private:
    const int k_;
public:
    A(int k) : k_(k) {}
    A() = delete;
    A(const A& other) : k_(other.k_) {}

    A& operator=(A const& other)
    {
        // do nothing
        return *this;
    }

    int get_k() const { return k_; }
};

int main(int argc, char** argv)
{
    A a1(5);
    A a2(0);

    a2 = a1;
}
Run Code Online (Sandbox Code Playgroud)

不会产生编译时错误。