布尔和双运算符重载

时间:2014-04-14 00:59:27

标签: c++ overloading operator-keyword

基本上我需要为boolean和double重载运算符。 对于布尔值,我需要重载&&,||和<< 对于double我需要重载:     + - * / ^&& || << 这是boolean.h文件

#ifndef BOOLEAN_H
#define BOOLEAN_H

#include "iostream";

using namespace std;

class Boolean {
public:
    Boolean();
    Boolean(const Boolean& orig);
    virtual ~Boolean();
    //overload the &&, ||, and << operators here.
private:

};

#endif

这是double.h文件

#ifndef DOUBLE_H
#define DOUBLE_H

class Double {
public:
    Double();
    Double(const Double& orig);
    virtual ~Double();
private:

};

#endif

1 个答案:

答案 0 :(得分:0)

   virtual ~Boolean();
   friend Boolean operator&&(const Boolean& lhs, const Boolean& rhs)
   {
       // assuming bool truth_ member... adjust as necessary
       return lhs.truth_ && lhs.truth_;
   }
   //similar for ||
   friend std::ostream& operator<<(std::ostream& os, const Boolean& b)
   {
       return os << (b.truth_ ? "True" : "False");
   }

private:

Double运营商也是如此。

或者,您可以在课外定义这些内容,如果他们不需要友谊,这可以说更清晰:

   Boolean operator&&(const Boolean& lhs, const Boolean& rhs)
   {
       // assuming bool is_true() member function... adjust as necessary
       return lhs.is_true() && lhs.is_true();
   }