【问题标题】:Accessing Value from constructor [closed]从构造函数访问值 [关闭]
【发布时间】:2017-02-15 22:52:16
【问题描述】:

在我的 isEmpty 函数中,我想检查对象是否处于安全的空状态,如果是则返回 true。当我在函数正上方的构造函数中声明的 denom = -1 时发生安全空。我如何访问这个? 编辑:抱歉,我误读了线路错误。我错过了另一行使用过的 denom,我修复了错误。很抱歉浪费您的时间:(

 using namespace std;

namespace sict{

class Fraction{
private:
    int num;                // Numerator
    int denom;            // Denominator
    int gcd();            // returns the greatest common divisor of num and denom


  int max();        // returns the maximum of num and denom
  int min();        // returns the minimum of num and denom

public:
    void reduce();     // simplifies a Fraction number by dividing the 
                      // numerator and denominator to their greatest common divisor 
    Fraction();                             // default constructor
    Fraction(int n , int d=1);               // construct n/d as a Fraction number
    void display() const;    
    bool isEmpty() const;
 };
};

**实现*

#include "Fraction.h"

using namespace std;

namespace sict
{
  Fraction::Fraction()
  {  
        denom =-1;              // safe empty state

  }
 bool Fraction::isEmpty() const
 {

 //How do I access denom
 }
}

【问题讨论】:

  • 和你在构造函数中做的一样吗?抱歉,我没听懂。
  • 你是怎么在构造函数中使用的?
  • isEmpty 是 Fraction 类的成员函数,因此所有成员变量/函数都可以访问。

标签: c++


【解决方案1】:

就像这样:

bool Fraction::isEmpty() const
{
    return denom == -1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-26
    • 2023-03-03
    • 2014-11-20
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多