Home > Net >  A question about class member function that returns a structure
A question about class member function that returns a structure

Time:09-03

I had a trouble when I read C Primer Plus.

class AcctABC
{
private:
    string fullName;
    long acctNum;
    double balance;
protected:
    struct Formatting
    {
         std::ios_base::fmtflags flag;
         std::streamsize pr;
    };
    const std::string & FullName() const {return fullName;}
    long AcctNum() const {return acctNum;}
    Formatting SetFormat() const;
    void Restore(Formatting & f) const;
public: 
    AcctABC(const std::string & s = "Nullbody", long an = -1,
                double bal = 0.0);
    void Deposit(double amt) ;
    virtual void Withdraw(double amt) = 0;
    double Balance() const {return balance;};
    virtual void ViewAcct() const = 0;
    virtual ~AcctABC() {}
};

and here are two definitions of class member funcions in the protected scope.

AcctABC::Formatting AcctABC::SetFormat() const
{
    Formatting f;
    f.flag = 
        cout.setf(ios_base::fixed, ios_base::floatfield);
    f.pr = cout.precision(2);
    return f; 
}
void AcctABC::Restore(Formatting & f) const
{
    cout.setf(f.flag, ios_base::floatfield);
    cout.precision(f.pr);
}

we can see the return of the first class member function, there is a AcctABC::,but in the declaration there isn't, and the argument of the second class member function, we needn't use the AcctABC::, I want to know why the rule is like this.

CodePudding user response:

This is about qualified names. The fully qualified name of the return struct is AcctABC::Formatting. However the AcctABC:: can be omitted if you are already in the scope of an AcctABC definition. That is why AcctABC:: is not necessary in the SetFormat declaration, or in the body of the SetFormat definition, or the parameter list of the Restore definition.

However the return type of a method definition outside of a class definition is not considered to be in the scope of the class, so there a fully qualified name is required.

I'm not certain exactly why this rule is as it is. I guess it has something to do with the fact that to implement a rule where the return type was in scope would mean the compiler having to read ahead to find the method definition before applying that to the return type. In other words the rule just makes things a little easier for the compiler.

  • Related