含const型成员变量的类的赋值构造函数

 

含const型成员变量的类的赋值构造函数

分类: 我的学习历程   1000人阅读  评论(0)  收藏  举报
iostream include 编译器 types class

#include <iostream>
using namespace std;


class Test
{
public:
 Test(int a,int b):i(a),j(b)
 {
 }
 Test(const Test& t):i(t.i),j(t.j)
 {

 }

 void show()
 {
  cout<<i<<","<<j<<endl;
 }

public:
 const int i ;
 int  j;

};


void main()
{
 Test t1(1,2);
 Test t2(t1);
 t1.show();
 t2.show();

 t1 = t2;
}

/*
error: no operator "=" matches these operands
            operand types are: Test = Test
   t1 = t2;
      ^
*/

对包含const成员变量的类而言,编译器不提供默认 赋值拷贝 ( = ) 函数的
需要自己定义
即使自己定义了,对其中的const变量也是不能做修改的
 Test& operator = (const Test& t) {
 //Some assign or copy
 //But const var can't be modified
         return *this;
 } 

你可能感兴趣的:(我的学习历程)