在下面的代码中,我没有得到
- 将 MyClass::~MyClass() 析构函数设为私有的用途/原因/好处?
- 由于析构函数是私有的,所以最后如何调用析构函数。
// myclass.h #include <iostream> class MyClass { public: static MyClass& GetInstance(); void Display(); private: MyClass(); virtual ~MyClass(); };
MyClass::MyClass() {
std::cout << "Constructor " << std::endl;
}
MyClass::~MyClass() {
std::cout << "Destructor" << std::endl;
}
MyClass& MyClass::GetInstance() {
static MyClass _instance;
return _instance;
}
void MyClass::Display() {
std::cout << "Hello" << std::endl;
}
// main.cpp
#include "myclass.h"
#include <iostream>
int main() {
MyClass::GetInstance().Display(); //case1
std::cout << "main finished!" << std::endl;
return 0;
}
//输出
Constructor
Hello
Destructor
// 编辑
如果我公开我的类的构造函数并删除 GetInstance() 函数。
> MyClass obj;
> obj.Display();
然后弹出如下错误
1>e:\programs\cpp_test\src\main.cpp(38): error C2248: 'MyClass::MyClass' : cannot access private member declared in class 'MyClass'
1> e:\programs\cpp_test\static_single_test.h(11) : see declaration of 'MyClass::MyClass'
1> e:\programs\cpp_test\static_single_test.h(6) : see declaration of 'MyClass'
1>e:\programs\cpp_test\src\main.cpp(38): error C2248: 'MyClass::~MyClass' : cannot access private member declared in class 'MyClass'
1> e:\programs\cpp_test\static_single_test.h(12) : see declaration of 'MyClass::~MyClass
'
问题:如何让 C++ 处理静态案例?是不是覆盖了私人行为?