private : const static A*p 有问题。。。。;这个指针如何初始化

daojin505 2009-04-24 12:19:34
c++中的禁用构造,够狠的,连自己的成员都构造不成了!



class A{

private:

A(){}

static A* pa;

};



如何初始化pa啊??期待解决啊.



如果想构造pa吧。。我又想禁止对构造的访问.



...........................下面是自己的想法:



据说const对象可以直接在类内初始化:



但是,问题是构造函数又不能在类内访问!!



莫非,c++禁止让自己构造自己?



难道我要建一个A类的姐妹类:



#include "stdafx.h"
#include <stdio.h>
#include <iostream.h>

class A{
private:
friend class ASister;
A(){}
public:
void hello() const {
cout<<"Hello!"<<endl;
}
};
class ASister{
private:
const static A* pa=new A();
public:
const static A* GetA(){
return pa;
}
};
const A* ASister::pa;

//const static A pa;

int main(int argc, char* argv[])
{
const A *a=ASister::GetA();
a->hello();
}


//上面的代码中,这句话有错误!!!!!!!!!为什么啊。。。。。



const static A* pa=new A();


...全文
152 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ljhiiiiiiii 2009-04-24
  • 打赏
  • 举报
回复
class A{

private:

A(){ A::pa = NULL; }

static A* pa;

};
sytstarac 2009-04-24
  • 打赏
  • 举报
回复
class A{
public:
A* get_A(){if(pa==NULL)pa=new A();return pa;}
private:

A(){}

static A* pa;

};
arong1234 2009-04-24
  • 打赏
  • 举报
回复
你还是应该在构造函数中初始化它
私有构造不是说永远不能用那个构造,永远不能用的构造函数是不存在的。只要你实例化这个变量,必然会构造它,最终肯定要初始化

个人不是很赞同使用const static类型的常量。因为编译器还没有广泛的支持,你使用这样的技术是非常有风险的
daojin505 2009-04-24
  • 打赏
  • 举报
回复
// Array.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <iostream.h>

class A{
private:
friend class ASister;
A(){}
public:
void hello() const {
cout<<"Hello!"<<endl;
}
};
class ASister{
private:
const static A* pa;
public:
const static A* GetA(){
return pa;
}
};
const A* ASister::pa=new A();

//const static A pa;

int main(int argc, char* argv[])
{
const A *a=ASister::GetA();
a->hello();
}
这样却可以。。。




songxinSQL 2009-04-24
  • 打赏
  • 举报
回复
#include "stdafx.h"
#include <stdio.h>
#include <iostream.h>

class A{
private:
friend class ASister;
A(){}
public:
void hello() const {
cout < <"Hello!" < <endl;
}
};
class ASister{
private:
const static A* pa=new A();
public:
const static A* GetA(){
return pa;
}
};
const A* ASister::pa;

//const static A pa;

int main(int argc, char* argv[])
{
const A *a=ASister::GetA();
a->hello();
}


//上面的代码中,这句话有错误!!!!!!!!!为什么啊。。。。。



const static A* pa=new A();


在类外定义静态数据成员时不能加static限定词!

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧