如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
Why Compiler do not provide default assignment operator if a class has non-static data membera of const or referance type in C++?
#include<iostream>
using namespace std;
class Test
{
int x;
int &ref;
public:
Test (int i):x(i), ref(x) {}
void print() { cout << ref; }
void setX(int i) { x = i; }
};
int main()
{
Test t1(10);
Test t2(20);
t2 = t1;
t1.setX(40);
t2.print();
return 0;
}
此程序给出编译器错误
引用和常量变量只能在构造时给出一个值。赋值运算符仅适用于已构造的对象。
相关文章:
- 为什么所有C++编译器都会崩溃或挂起此代码
- 为什么C++编译器没有检测到正确声明的类?
- 为什么布尔开关语句有编译器警告?
- 为什么编译器将其解析为函数指针而不是递归调用?
- C++为什么我的编译器成功了,但我的计算机给出了调试错误?
- C++初学者:为什么我的编译器根据我的循环返回"name not found"?
- 为什么我的编译器无法弄清楚这种转换,它何时存在?
- 为什么编译器说"candidate template ignored: couldn't infer template argument 'InputIterator'"?
- 为什么编译器不检查被覆盖函数的存储类?
- 为什么编译器在使用"无常量复制构造函数"时抱怨?
- 为什么 std::count 比 MSVC 编译器的普通循环慢,但与 GCC 相等?
- 为什么 gcc 编译器标志未知?
- 当类型适当的构造函数可用时,为什么一个编译器尝试使用已删除的副本构造函数
- C 17 GCC编译器为什么会发出有关未定义的警告
- Clang 编译器为什么无法编译以下variadic模板代码
- 编译器为什么抱怨对齐
- 编译器为什么要将浮点数字的位数固定为6
- 编译器为什么要生成此程序集
- vtkCharts库既不适用于Visual Studio,也不适用于GCC编译器 - 为什么?
- 在c++中,当常量也可以工作时,编译器为什么选择非常量函数