您的位置:首页 > 产品设计 > UI/UE

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

2006-06-21 11:17 513 查看
// 一般认为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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐