簡體   English   中英

繼承的模板類成員在鏈構造函數中測試正常,但此后“丟失”

[英]Inherited template class member tests fine in chain constructor, but is “lost” thereafter

我的基類class Foo是一個模板類,它具有以下構造函數:

//Declarations
template <class T>
class Foo
{
public:
    Foo::Foo(std::string& root);
    MemberClass obj;
}

template <class T>
Foo<T>::Foo(std::string& root)
{
    MemberClass obj(root); // initialize the member object
    obj.getRoot(); // Prints the string
    // ...
}

它有一個子類,其構造如下:

template <class T>
Bar<T>::Bar(std::string& root)
    : Foo<T>(root)
{
    //...
}

template<class T>
void
Bar<T>::accessObj()
{
    this->obj.getRoot();
    // Prints the empty string
}

即使沒有錯誤生成,這也會帶來意外的行為。 在這種情況下, getRoot()將返回空字符串。

我已經通過更改Foo構造函數進行了測試,如下所示:

{
    MemberClass obj(root);
    std::cout << &obj << std::endl;
}

Bar構造函數是這樣的:

//...
    : Foo<T>(root)
{
    std::cout << &this->obj << std::endl;
}

輸出給出了內存中的兩個不同位置,這完全讓我震驚。 為什么會這樣呢? 我如何解決它?

您的構造函數最好如下所示:

template <class T>
Foo<T>::Foo(std::string& root)
    : obj(root) // initialize the member object
{
    obj.getRoot(); // Prints the string
    // ...
}

以前,您是在Foo構造函數中構造一個臨時obj並將其丟棄,根本沒有初始化您的成員變量。

如果您使用的是GCC,則-Wshadow選項可能有助於捕獲此錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM