Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 继承的模板类成员在链构造函数中测试良好,但为;“丢失”;此后_C++_Templates_Inheritance - Fatal编程技术网

C++ 继承的模板类成员在链构造函数中测试良好,但为;“丢失”;此后

C++ 继承的模板类成员在链构造函数中测试良好,但为;“丢失”;此后,c++,templates,inheritance,C++,Templates,Inheritance,我的基类,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); //

我的基类,
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
    // ...
}
构造函数,如下所示:

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

std::cout obj您的构造函数最好如下所示:

template <class T>
Foo<T>::Foo(std::string& root)
    : obj(root) // initialize the member object
{
    obj.getRoot(); // Prints the string
    // ...
}
模板
Foo::Foo(std::string和root)
:obj(root)//初始化成员对象
{
obj.getRoot();//打印字符串
// ...
}
以前,您在Foo构造函数中构造了一个临时的
obj
,然后将它扔掉,从没有初始化过成员变量


如果您使用的是GCC,那么选项-Wshadow可能有助于发现这个错误。

我很抱歉。我应该在声明中包含这一点,MemberClass obj是作为接口的一部分包含在声明中的。我想我从您发布的内容中猜到了您的声明的样子。您认为我的答案正确与否?如果“obj”是这个类的成员,在Foo实例化之后它是如何被丢弃的?(顺便说一句,我正在测试你的答案,但也在做晚餐:-)你有两个东西叫做obj。这个类的成员,和一个由这个表达式构造的:
MemberClass obj(root)这是你的问题。嗯,我认为无论使用哪种类型,阴影都是一致适用的。实际上,请尝试使用GCC的-Wshadow选项或编译器或静态代码分析工具存在的任何类似警告。
template <class T>
Foo<T>::Foo(std::string& root)
    : obj(root) // initialize the member object
{
    obj.getRoot(); // Prints the string
    // ...
}