【发布时间】:2021-09-08 08:36:23
【问题描述】:
这是一个正在创建的基本直方图,但我的问题在 TH1F *hist=new TH1F("hist", "Histogram", 100, 0, 100); 我知道指针有助于将地址存储到对象,而构造函数有助于将值输入到类中的对象,但是这一行发生了什么?是否已创建指针并将其定义为构造函数? “新”有什么用?
// Creating a histogram
void tut1()
// Void functions do not return values, simply prints a message so I assume our message here is the histogram, histograms display values but they are not themselves not values
{
TH1F *hist=new TH1F("hist", "Histogram", 100, 0, 100);
// This is just a constructor
// TH1F is a inherited class from the base class TH1
//(the name of the histogram, the title of the histograms, number of bins, start of x axis, and ending paramater of x axis)
// Here we are accessing TH1F the capital F is for floats and we use this to use 1D histograms
// To Fill the histogram we use
hist->Fill(10);
hist->Fill(40);
// Add titles for the axis's
hist->GetXaxis()-SetTitle("X Axis");
hist->GetYaxis()-SetTitle("Y Axis");
TCanvas *c1 = new TCanvas();
hist->Draw();
// Tcanvas is used to draw our plot it is the window that is used to display our image
}
【问题讨论】:
-
如果您的初学者书籍没有清楚地解释
new的作用,我强烈推荐 a good book。 -
你最好习惯 cmet 是骗子。 “//这只是一个构造函数”严格来说是无意义的。它是对构造函数的调用而不是构造函数
-
“构造函数有助于向对象输入值”。构造函数创建对象。 “创造”的另一个词是“构造”。
-
构造函数不是对象。它们将内存转换为类的实例(通常称为“对象”,但请注意as object has a much broader meaning in C++)。构造函数完成后,指针指向该类的一个实例。通常你根本不需要指针。在 C++ 中,通常最好尽可能使用Automatic allocation (
TH1F hist("hist", "Histogram", 100, 0, 100);)。这消除了手动管理new提供的分配的需要 -
坦率地说,你把基本术语弄错了,真的应该花一些时间看一些介绍性的书,因为 C++ 不是一种你可以通过查看随机代码示例来学习的语言。见这里:stackoverflow.com/questions/388242/…
标签: c++ root-framework