简体   繁体   中英

What do you call a member function that follows a member function and how do I write one?

What do you call function that follows a member function and modifies the return value and how do I write one?

In other words how do I successfully write:

std::cout << box.getVolume().inCubicFeet();

std::cout << box.getVolume().inCubicCentimeters();

For that to work getVolume() needs to return an object of type Volume ( or even a reference to an object of type Volume & ), so that whatever method follows you are able to invoke it on said object. For instance:

class Volume{
    ...
    int inCubicFeet() const {
        //convert it and return it
    }
    int inCubicCentimeters() const {
        //convert it and return it
    }
};


class Box{
    Volume v; //volume object that is initialized somewhere 
              //(either in the constructor of Box or in a method like setVolume)
    ...
    Volume const& getVolume() const {
        return v;
    }
};

box.getVolume() needs to return an object of a class for which a function inCubicFeet() is defined which returns a value for which std::ostream has an overloaded << operator (although you are allowed to define your own overloads). For that second part, a double would suffice.

It is called "member function of the return type". There is nothing special about those methods. The code could be written like this:

const Volume& v = box.getVolume();    // my guess on what the return type is
std::cout << v.inCubicFeet(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM