一个永远无法被初始化的指针:

xiaoxiao2021-02-28  96

c++中的禁用构造,够狠的,连自己的成员都构造不成了!

 

class A{

private:

     A(){}

     static A* pa;

};

这样pa就永远无法初始化,如下代码会报错:

#include <cstdlib> #include <iostream> #include <stdio.h> using namespace std; class A{ private: friend class ASister; A(){} static A* pa; public: void hello() const { cout<<"Hello!"<<endl; } }; static A::A*pa = new A(); //const static A pa; int main(int argc, char* argv[]) { a->hello(); system("PAUSE"); } 报错如下: 10 C:\Users\Administrator\Documents\main.cpp `A::A()' is private

 

这就是C++的一个大缺陷。

#include <cstdlib> #include <iostream> #include <stdio.h> using namespace std; class A{ private: A(){} static A* pa; public: void hello() const { cout<<"Hello!"<<endl; } static A* getA(){ if(!pa)pa = new A(); return pa; } }; A*A::pa; //const static A pa; int main(int argc, char* argv[]) { A* a = A::getA(); a->hello(); system("PAUSE"); }

 

 时隔几年回过头来再看,还是蛮有意思。呵呵。C++语法真怪异。

 

 

 

 

转载请注明原文地址: https://www.6miu.com/read-74840.html

最新回复(0)