c++ - 如果类在 C++ 中具有 const 或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
问题描述
#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;
}
该程序给出编译器错误
解决方案
引用和 const 变量只能在构造时给定一个值。赋值运算符仅适用于已构造的对象。
推荐阅读
- c# - 基本 WebSocket 聊天
- android - RotateAnimation 获取图像的当前角度
- java - 创建缓存时如何将所有缓存名称及其数据放入 List<> 中?
- neural-network - 以逐个字符的方式生成注意力文本
- c# - 我怎么知道我的进程在 c# 中被杀死了?
- c++ - 是否可以在 C++ 中将类标记为非最终/可派生?
- excel - 如何从 Excel 中获取数据并使用 MailMerge 将其合并到 Word 中?
- angular - Firefox 和 Chrome 更新破坏了 Angular 应用程序
- excel - 使“选择”起作用的问题
- c# - 如何在 OData V1 中使用 nextlink?