如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?

Why Compiler do not provide default assignment operator if a class has non-static data membera of const or referance type in C++?

本文关键字:编译器 为什么 数据成员 赋值运算符 默认 静态 C++ 引用类型 常量 如果      更新时间:2023-10-16
#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;     
} 

此程序给出编译器错误

引用和常量变量只能在构造时给出一个值。赋值运算符仅适用于已构造的对象。