c ++ - 重载数组下标运算符

时间:2014-06-28 18:47:55

标签: c++

我正在尝试为从mysqlpp::StoreQueryResult库中的mysql++继承的类提供自定义异常处理机制。但我发现真正难以做的是找到一种方法来引用类中的实际对象,所以我无法正确使用向量操作at()以便在索引处检索值。

这是标题

/* MySQLQueryResult.h */


#ifndef MYSQLQUERYRESULT_H
#define MYSQLQUERYRESULT_H

#include <mysql++.h>
#include <result.h>

namespace  MinesScanner {

    namespace MoonStone {

        class MySQLQueryResult : public mysqlpp::StoreQueryResult  {
        public:

            MySQLQueryResult();


            MySQLQueryResult(const MySQLQueryResult &other);

            MySQLQueryResult& operator=(const MySQLQueryResult &other);

            mysqlpp::Row& operator[](int index);

        private:

            int _dat;



        };

    }

}

#endif  /* MYSQLQUERYRESULT_H */

这是源文件

/* MySQLQueryResult.cpp */

#include "MySQLQueryResult.h"

namespace MinesScanner {

    namespace MoonStone {

        MySQLQueryResult::MySQLQueryResult( )
    : StoreQueryResult( )
    {
    }

    MySQLQueryResult::MySQLQueryResult( const StoreQueryResult &ob )
    : StoreQueryResult( ob )
    {
    }

    MySQLQueryResult& MySQLQueryResult::operator=( const StoreQueryResult &ob )
    {

        StoreQueryResult::operator=( ob ) ;
        return *this ;

    }

    mysqlpp::Row& MySQLQueryResult::operator[]( int index )
    {


        try {

            std::cout << " Called " << this->at( index ) << std::endl ;
            return this->at( index ) ;
        } catch ( std::exception& excpn_ob ) {
            std::cerr << " Exception caught : " << excpn_ob.what( ) << std::endl ;
        }


    }


    }

}

一个简单的用法示例将更清楚地显示我想要实现的目标。

#include "MySQLQueryResult.h"

int main() {
StoreQueryResult lisres = getMinesData( ( string ) row.at( 0 ) ) ; // returns StoreQueryResult object storing the result

cout << lisres[0][7] << endl; // outputs "Falkreath Stormcloak Mines"

MySQLQueryResult my_lisres = getMinesData( ( string ) row.at( 0 ) ) ; // returns StoreQueryResult object storing the result

cout << my_lisres[0][7] << endl; // ERROR!

}

所以我基本上想要添加更多边界检查,检查空值,并使用类operator[]中的MySQLQueryResult处理out_of_range异常,但它不起作用。

我希望能够使用数组下标访问MySQLQueryResult对象。要么我得到垃圾值或者Seg错误。请让我知道如何做到这一点

1 个答案:

答案 0 :(得分:3)

  

但它不起作用

看起来also need const subscript operator版的const mysqlpp::Row& operator[](int index) const;

{{1}}