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

关于类中成员函数定义类的对像

arterforyou 发布于 2012-02-01 21:44, 663 次点击
我是C++的初学者,最近一个朋友讲一个类的成员函数中可以定义类的对像,举的例子是
class A{
void ff()
{
A a;
}
}
,我在网上搜了一下,没有过多关于这个的说法,毕竟是初学者,所以见识的比较少,还请高手可以指点一下。谢谢。
7 回复
#2
rjsp2012-02-02 08:23
为什么不可以?
#3
BianChengNan2012-02-02 10:40
我觉得像楼主这种写法应该不能通过编译吧。。。
class A{
void ff()
{
A a;  //这个应该不行吧,毕竟A还没定义完,换成其他类应该可以 如,B b
}
}
#4
lz10919149992012-02-02 12:39
This works because the language definition states that no inline functions in a class shall be evaluated until the closing brace of the class declaration.
这是Thinking in C++内联函数这一章里面说的,在类声明的右大括号之前(类声明结束),一个类中没有一个内联函数应该计算(这样任意一个内联函数就能知道这个类中的所有成员)。

[ 本帖最后由 lz1091914999 于 2012-2-2 12:41 编辑 ]
#5
BianChengNan2012-02-02 15:31
以下是引用lz1091914999在2012-2-2 12:39:43的发言:

This works because the language definition states that no inline functions in a class shall be evaluated until the closing brace of the class declaration.
这是Thinking in C++内联函数这一章里面说的,在类声明的右大括号之前(类声明结束),一个类中没有一个内联函数应该计算(这样任意一个内联函数就能知道这个类中的所有成员)。
看错了楼主的意思了。。。

看成了

class A{
  A a;   
  void fun(){ }
};
实在是抱歉啊

[ 本帖最后由 BianChengNan 于 2012-2-2 15:35 编辑 ]
#6
我是菜鸟C2012-02-02 20:12
要先声明吧。。。
#7
arterforyou2012-02-03 11:01
回复 2楼 rjsp
请问能否写一个关于这个函数的简单调用?
#8
arterforyou2012-02-03 11:03
回复 5楼 BianChengNan
谢谢你的回答。依然能让我这个新手多一点知识。
1