我忘记在类名的前面添加对象名,但是代码仍在编译并且构造函数被调用。我真的很困惑这里实际发生了什么。这不是意味着我们可以在不创建对象的情况下调用构造函数吗?
我的代码:
#include<iostream>
using namespace std;
class PrintJobs
{
private:
int nPages;
static int nTrayPages;
static int nJobs;
public:
PrintJobs(int np) : nPages(np)
{
nJobs++;
cout << "Printing " << nPages <<"pages" << endl;
}
~PrintJobs()
{
--nJobs;
}
static int getJobs()
{
return nJobs;
}
static int checkPages()
{
return nTrayPages;
}
static void loadPages(int n)
{
nTrayPages += n ;
}
};
int PrintJobs::nTrayPages = 500 ;
int PrintJobs::nJobs = 0 ;
int main()
{
cout << "Jobs " << PrintJobs::getJobs() << "\n" ;
cout << "Pages " << PrintJobs::checkPages() << "\n";
PrintJobs(10); /// This is the line I am confused about.
cout << "Jobs " << PrintJobs::getJobs() << "\n" ;
cout << "Pages " << PrintJobs::checkPages() << "\n";
{
PrintJobs p(30) , p2(20);
cout << "Jobs " << PrintJobs::getJobs() << "\n" ;
cout << "Pages " << PrintJobs::checkPages() << "\n";
PrintJobs::loadPages(100);
}
cout << "Jobs " << PrintJobs::getJobs() << "\n" ;
cout << "Pages " << PrintJobs::checkPages() << "\n";
}
输出:
Jobs 0
Pages 500
Printing 10pages
Jobs 0
Pages 500
Printing 30pages
Printing 20pages
Jobs 2
Pages 500
Jobs 0
Pages 600