C ++:检查条件语句中对象是否为空

时间:2014-03-23 17:49:51

标签: c++

您如何检查对象是否为空,如果是,则运行一段代码?

函数原型如下所示:

bool Order::add(int n)

我需要检查n是否大于0且对象不为空。(数据成员为0或null)我真的不确定如何执行此操作来检查对象是否为空,因为我不能在条件中使用* this。任何帮助,将不胜感激。

这是班级:

#include "ean.h"

class Order {
    int copies;
    int delivered;
    bool filled = false;
    EAN eanno;
public:
    Order();
    Order(const EAN& ean);
    EAN& getEAN();
    int outstanding() const;
    bool add(std::istream& is);
    bool add(int n);
    bool receive(std::istream& is);
    void display(std::ostream& os) const;
};
std::ostream& operator<<(std::ostream& os, const Order& order);

以下是两个构造函数:

Order::Order() {
    copies = 0;
    delivered = 0;
    this->eanno;
}

Order::Order(const EAN& ean) {
    Order();
    this->eanno = ean;
}

2 个答案:

答案 0 :(得分:1)

没有关于班级的任何信息,很难回答。这个怎么样 ? :

bool Order::add(int n)
{
   if( n > 0 )
      if( member1 != 0 || member2 != 0 || member3 != 0 )
      {
         ... // do something
      }
}

或许我不明白这个问题?

答案 1 :(得分:0)

我认为你问的是测试if (*this == 0)哪个不是你想要的,因为*this总是由构造函数初始化,永远不会返回0或nullptr。你想要测试它的成员。

为了清晰起见,您应该为您的类定义empty()(如果它尚不存在):

bool Order::empty() const {
  return m1 == 0 && m2 == nullptr;  // whatever conditions you use to define whether your object is null goes here. Don't test on *this because it will always be a constructed object, never null.
}

bool Order::add(const int n) {
   if (n > 0 && empty()) { 
     ... // your code goes here
     return true;
   }
   return false;
}

如果你没有改变结构中的任何东西,请考虑将其设为const。

相关问题