简体   繁体   中英

Call class method without parentheses in c++

Some c++ STL containers provide getters like

Foo.first

Foo.second

which apart from being very practical, improve code readability. Now suppose that I want to reproduce that feature in one of my own classes. Is it possible to define methods like

Matrix.components

Matrix.size

instead of

Matrix.components()

Matrix.size()

(same but without parentheses)? How could it be achieved?

The .first and .second members are data, not code. Thus it doesn't make sense to "call" them. You methods aren't data, they're code, so you'd have to call them using () . Note that .size() is a method on all STL containers, never a data member.

No, because this is how you access public member variable in C++.

The container you refer to must be an std::pair and that's its public member variables (the two elements of the pair) that are accessed this way, ie data and not functions.

For your matrix, either make these member variables (but that's a bad idea regarding encapsulation), or leave them as functions (like many container in the standard lib do).

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