- 论坛徽章:
- 0
|
原帖由 3040602024 于 2007-6-2 22:24 发表
class A
{
int j;
public:
A(){cout<<"heo"<<endl;}
~A(){cout<<"endl\n";}
};
main()
{
A::A::A();
A aaaa();
}
都没调用构照函数。谁能说一下这是什 ...
楼主的程序涉及到 C++ 中的两大重要内容--名字查找(Name lookup)以及歧义解析(Ambiguity resolution),都是很迷惑人的东西。
其中的歧义解析(即关于 A aaaa(); 的问题)详见下面这个帖子中我的解释:
http://bbs.chinaunix.net/viewthread.php?tid=847260
在这里主要说明 A::A 的含义以及诸如 A::A::A 这样二重以上的限定非法的问题。
根据目前 C++ 标准(1998版 和 2003版)的规定,如果 class-name::class-name 中的 class-name 指的是同一个类名,则这种形式表示的是 class-name 类的 构造函数成员,而不是类本身,即 class-name::class-name 不是一个 类型。
假设 A 是一个类名,对 A::A 的使用情况作进一步的说明。如上所言,A::A 是类 A 的构造函数,不是类型。下面在类定义外面的使用情况都应该是非法的;
- A::A a; // error, A::A is not a type name.
- struct A::A a2; // error, A::A is not a type name.
- A::A::A a1; // error, A::A is not a type name.
- // The left operand of the second :: operator is A::A, and
- // it should be a class or namespace name, but it is not.
- A::A func(); // error, A::A is not a type name.
- A::A(); // error, redeclaration of a member function is not allowed.
- &A::A; // error, constructors (and destructors) have no address.
- A a;
- a.A::A(); // error, constructor cannot be called explicitly.
复制代码
根据现行标准,A::A 能够合法使用的唯一场所是在位于类定义之外的构造函数的定义中:
- A::A() { // ok, A::A donates the constructor.
- // ...
- }
复制代码
这也从一个侧面告诉我们:在类定义中声明(包括定义)的构造函数不应该在前面再加上类名来修饰:
- struct A {
- A(); // ok, A is an unqualified declarator-id.
- // A::A(); will be an error, since all members of class A
- // declared in class A definition cannot be qualified.
- };
复制代码
然而有的编译器允许使用诸如 A::A::A::A 这样的多重修饰,是因为把 A::A 作为类型来处理的,特别是在有明确类型语义要求的上下文环境中。虽然与标准不符,但是这样做有一定的道理。
因此,目前已经有人提案,建议 A::A 不单独作为构造函数解释,而是在一些只能作类型解释的语义环境下使其成为类型 A。比如下面的情况:
- A::A a; // error, A::A is not a type name.
- struct A::A a2; // ok, a2 is an object of type A
复制代码
这已经写在标准草案中。至于能否成为正式的标准,还需拭目以待。 |
评分
-
查看全部评分
|