关于赋值操作符的重载: 这个程序为什么能在g++上编译通过?

// 一般认为gcc是学习C/C++的最佳编译器。可是下面这个程序在g++3.4.4上竟然可以编译通过。

#include <vector>
#include <iostream>
using namespace std;

class val_box
{
private:
    int val;
public:
    int get()
    {
        return val;
    }
    void set(int new_val)
    {
        val = new_val;
    }    
    val_box& operator= (val_box& right)   //  实际上, const 是必需的
    {   // 赋值操作符的重载
        val = right.val;
        return *this;
    } 
};

class query
{
private:
    vector<val_box> val_box_collection;
public:
    void Insert(int val)
    {
        val_box temp_val_box;
        temp_val_box.set(val);
        val_box_collection.push_back(temp_val_box);
    }
    friend ostream& operator<< (ostream& os, query& right)
    {
        for(vector<val_box>::iterator iter = right.val_box_collection.begin();
            iter != right.val_box_collection.end(); ++iter)
        {
            os << (*iter).get() << "/t";
        }       
        return os;
    }
};


int main()
{
    query test_class;
    test_class.Insert(1);
    test_class.Insert(2);
    test_class.Insert(3);
    cout << test_class << endl;
    cin.get();
    return 0;
}


/*
vc2005的错误描述:
Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'const val_box' (or there is no acceptable conversion) 

Digital Mars 的错误描述:
C:/dm/bin/../stlport/stlport/stl/_algobase.h(327) : Error: need explicit cast for function parameter 1 to get
from: const val_box*
to  : val_box*
C:/dm/bin/../stlport/stlport/stl/_algobase.h(139) : Error: need explicit cast for function parameter 1 to get
from: const val_box*
to  : val_box*
C:/dm/bin/../stlport/stlport/stl/_algobase.h(335) : Error: need explicit cast for function parameter 1 to get
from: const val_box*
to  : val_box*
main.cpp:
--- errorlevel 1
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值