【发布时间】:2012-07-04 18:02:04
【问题描述】:
假设我有一个类Baz,它按顺序从类Foo 和Bar 继承。 Bar 类的构造函数接受一个指向 Foo 对象的指针。我想做的是将this 作为Foo 对象传递给Bar 构造函数:
Baz () : Foo(), Bar(this) {}
一个工作示例:
#include <iostream>
class Bar;
class Foo {
public:
virtual ~Foo() {}
virtual void parse_bar (Bar&) const = 0;
};
class Bar {
private:
const Foo * parser;
public:
Bar (const Foo * parser_in) : parser(parser_in) {}
virtual ~Bar() {}
void parse_self () { parser->parse_bar (*this); }
};
class Baz : public Foo, public Bar {
public:
Baz () : Foo(), Bar(this) {}
virtual void parse_bar (Bar &) const { std::cout << "Hello World\n"; }
};
int main () {
Baz baz;
baz.parse_self();
}
这恰好可以在我的计算机上使用我的编译器(用其中几个进行测试)工作。然而,2003 年标准的第 9.3.2 节让我有点不安,我可能只是走运了,以这种方式使用 this 是未定义的行为。严格来说,初始化列表在构造函数的主体之外。这是相关的文字,强调我的:
9.3.2
this指针
在非静态成员函数的body中,关键字this是一个非左值表达式,其值为调用该函数的对象的地址。
那么我的使用是合法且定义明确的,还是未定义的行为?
【问题讨论】:
标签: c++ this language-lawyer initializer-list