简体   繁体   English

在 C++ 中调用不带括号的类方法

[英]Call class method without parentheses in c++

Some c++ STL containers provide getters like一些 C++ STL 容器提供 getter,如

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..first.second成员是数据,而不是代码。 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.请注意, .size()是所有 STL 容器上的方法,而不是数据成员。

No, because this is how you access public member variable in C++.不,因为这是您在 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.您引用的容器必须是std::pair并且这是以这种方式访问​​的公共成员变量(对的两个元素),即数据而不是函数。

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).对于您的矩阵,要么创建这些成员变量(但这对于封装来说是个坏主意),要么将它们保留为函数(就像标准库中的许多容器一样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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