我正在设计一个类,该类应具有名为的const数据成员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
}
这是它生成的错误:
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.
我想我知道为什么编译器会这样做。我想要复制到的类的实例必须先存在,然后才能复制到K
该对象,并且如果它是const,则不能在该目标实例中分配给它,就像我在上面尝试的那样。
我对这个问题的理解正确吗?如果是这样,是否有解决此问题的方法?也就是说,我可以为我的类定义一个复制构造函数,并且仍然提供K
类似const的保护吗?
在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";
}
输出:
a1.k_ = 5
a2.k_ = 5
在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;
}
产生编译时错误:
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
在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;
}
不产生编译时错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句