假設我有一個類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
指針
在體的非靜態成員函數的,關鍵字this
是非左值表達式,其值是對象的地址爲此函數被調用。
那麼,我的用法是否合法且定義明確,還是未定義的行爲?
比我的答案要清楚得多,我會稍微刪除一下。 – GManNickG
@GManNickG Dont!評論可能對新手有用 – TeaOverflow
@Evgeni:對不起。 :)新手!有關類繼承的問題? - > [圖書清單](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – GManNickG