首页 > 解决方案 > 如果类在 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;     
} 

该程序给出编译器错误

标签: c++

解决方案


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


推荐阅读