c++类和静态

发布于 2024-12-29 04:18:38 字数 171 浏览 4 评论 0原文

我有一个关于课程设计的问题。我想要一个封装了一堆相关函数的类。例如一个统计类,它有静态函数来计算算术平均值、经验方差等。或者一个物理类,它可以计算抛射运动、波动等。

你如何在 main 中引用这些函数?参考统计示例,在 Java 中我会执行 Statistics.calcMean()

I have a question regarding class design. I want to have a class that encapsulates a bunch of related functions. For instance a Statistics class that would have static functions to calculate the arithmetic mean, empirical variance, etc. Or a physics class that would calculate projectile motion, wave-motion, etc.

How do you reference these function in main? Referring to the statistics example, in Java I would do Statistics.calcMean().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

青春有你 2025-01-05 04:18:38

统计::calcMean()。您还可以使用命名空间而不是静态类成员。

Statistics::calcMean(). You could also use a namespace instead of static class members.

客…行舟 2025-01-05 04:18:38

如果不同的函数之间根本没有共享状态,那么最好不要创建类,而是创建命名空间:

namespace Statistics {
   // probably templated on the type of the value and the container...
   double calcMean( std::vector<double> const & values );
}

然后从 main 调用它:

int main() {
   std::vector<double> values = create_values();
   std::cout << "mean=" << Statistics::calcMean( values ) << std::endl;
}

If there is no shared state at all among the different functions, it might be a better idea not to create a class but rather a namespace:

namespace Statistics {
   // probably templated on the type of the value and the container...
   double calcMean( std::vector<double> const & values );
}

And then you call it from main:

int main() {
   std::vector<double> values = create_values();
   std::cout << "mean=" << Statistics::calcMean( values ) << std::endl;
}
浅笑轻吟梦一曲 2025-01-05 04:18:38

使用 :: 引用静态类成员:Statistics::calcMean()

Use :: to reference static class members: Statistics::calcMean()

[浮城] 2025-01-05 04:18:38

将静态方法定义为:

static void calcMean();

调用方式:

Statistics::calcMean();

Define the static methods as:

static void calcMean();

Invoke by:

Statistics::calcMean();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文