注册 登录
编程论坛 C++教室

前项引用声明

cclearner 发布于 2007-07-05 21:02, 1317 次点击
前项引用声明一个类以后,在没声明完整类之前能做什么?
可以声明此类的指针,但对象就不行。可以此类的形参,但是具体到底可以做那一些呢?
8 回复
#2
cclearner2007-07-05 23:50
没人能指点一下迷津么?
我的前项引用声明。。。。。。
#3
野比2007-07-05 23:58

没时间了... 明晚来看看... 估计HJin, aipb等很快能给你回答...
祝顺利解决...

#4
HJin2007-07-06 06:20
回复:(cclearner)前项引用声明

/*---------------------------------------------------------------------------
File name: declVSdefn.cpp
Author: HJin (email: fish_sea_bird [at] yahoo [dot] com )
Created on: 7/5/2007 15:18:47
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762

Modification history:
===========================================================================


The following code compiles under MS VS 2005.

defn === definition
decl === declaration

forward decl is used when you need to know the name
of a type before the defn of that type.

If you don't have defn of a type, you can only play with the type name.
You cannot do anything that is meaningful for that type, simply because
you cannot construct an object of that type.

*/

#include <iostream>
#include <string>

using namespace std;


class B; // forward decl

class A
{
public:
void f(B& rObjB, B* pObjB, B objB); // ok --- you declare f() instead of define

/**
wrong --- you are defining g(). need to define B first.
*/
/*
void g(B& rObjB, B* pObjB, B objB)
{

}
*/

private:
//B objB; // wrong --- need to know the defn to allocate memory space for objB
B& rObjB; // reference --- ok
B* pObjB; // pointer --- ok
static B sObjB; // static --- ok

};

int main(int argc, char** argv)
{

return 0;
}

#5
aipb20072007-07-06 11:34
ls的分析很完整了,你看不懂的话,我就说说:

我的理解是这样的,前项声明类时,该类并没有定义。
所以任何试图给这个类分配内存的操作将导致错误。

简单的说就是定义一个对象不允许。
然而,定义指向该类的指针和引用是允许的。
作为成员函数原型声明中参数和返回类型也可以,但是这是仅能声明,不能定义。
#6
孤魂居士2007-07-06 15:32

又学了个知识
#7
cclearner2007-07-06 16:06
哦,三位斑竹的回答,我明白了哦!不知能不能实际应用的好。
嗯,HJin的英文看懂了,不过有一点不明白。
为什么private里static的行,不是static的就不行呢?
thank you
#8
aipb20072007-07-06 16:18
回复:(cclearner)哦,三位斑竹的回答,我明白了哦!...
知道static声明定义是分开的吧?

比如在类里
static B sObjB; //这仅仅声明
类外
B A::sObjB; //这是定义,在这时sObjB才会被分配内存
//并且,这个定义要正确,必须在类B定义之后
#9
cclearner2007-07-06 16:27
o ,对了,是这样的哎,嗯,一般的需要声明时分配内存,这个就不用了。
嗯,懂了~QQQ
1