Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.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+中的构造函数+;0x 让我说下面的代码是我们期望成为下一个C++标准: int f(int x) { std::cout << x; return x * x; } struct A { A(int x) : m_x(x) {} int m_x; }; struct B : A { using A::A; B() : m_y(f(m_x)) {} int m_y; }; int main() { B(5); } intf(intx) { std::cout_C++_Constructor_C++11 - Fatal编程技术网

继承C+中的构造函数+;0x 让我说下面的代码是我们期望成为下一个C++标准: int f(int x) { std::cout << x; return x * x; } struct A { A(int x) : m_x(x) {} int m_x; }; struct B : A { using A::A; B() : m_y(f(m_x)) {} int m_y; }; int main() { B(5); } intf(intx) { std::cout

继承C+中的构造函数+;0x 让我说下面的代码是我们期望成为下一个C++标准: int f(int x) { std::cout << x; return x * x; } struct A { A(int x) : m_x(x) {} int m_x; }; struct B : A { using A::A; B() : m_y(f(m_x)) {} int m_y; }; int main() { B(5); } intf(intx) { std::cout,c++,constructor,c++11,C++,Constructor,C++11,使用A::A;在派生类中隐式声明B(int)。就是这样 程序的其余部分不应按预期工作。因为您正在使用B(5)调用B(int),这会使m_y未初始化 请参见比亚恩·斯特劳斯特鲁普网站上的示例: struct B1 { B1(int) { } }; struct D1 : B1 { using B1::B1; // implicitly declares D1(int) int x; }; void test() { D1 d(6); // Oops: d.

使用A::A;
在派生类中隐式声明
B(int)
。就是这样

程序的其余部分不应按预期工作。因为您正在使用
B(5)
调用
B(int)
,这会使
m_y
未初始化

请参见比亚恩·斯特劳斯特鲁普网站上的示例:

struct B1 {
    B1(int) { }
};

struct D1 : B1 {
    using B1::B1; // implicitly declares D1(int)
    int x;
};

void test()
{
    D1 d(6);    // Oops: d.x is not initialized
    D1 e;       // error: D1 has no default constructor
}

同一链接中的另一个示例:

struct D1 : B1 {
        using B1::B1;   // implicitly declares D1(int)
        int x{0};   // note: x is initialized
    };

    void test()
    {
        D1 d(6);    // d.x is zero
    }

m_y将是未初始化的,通过使用A::A,您将得到如下结果:B::B(int x):A::m_x(x){}。或者是:)C++实际上选择编译代码时出错,因为您没有为A提供默认构造函数。这不是一个未定义的行为:)如果D1有一个默认构造函数,它会在运行行“D1 d(6)”时运行吗?他的示例没有声明D1的默认构造函数。当然,x不会被初始化,不管“使用B1:B1”。然而,我的示例声明了一个默认构造函数。@Clinton:是的。但是在您的示例中没有调用默认构造函数。因此,不管您是否定义它,您都会调用隐式声明的构造函数,即
B(int)@纳瓦兹:为什么?在调用C++默认构造函数之后,什么原理是没有的?在C++中没有任何实例可以创建一个对象而不调用它的构造函数。+ 1 @克林顿:如果你想用B1::B1 < /C> >编译器的方式来解释<代码>,那么理解它可能会更简单。(在这个特殊情况下)到
D1(int_uux):B1(uux){
。请注意,这并不意味着调用B1构造函数,而是创建一个将调用B1构造函数的D1构造函数。该构造函数没有显式修改成员
x
,因为它的类型为
int
,这意味着它未初始化。除非根据最后一个代码段,它使用初始化sy声明中的ntax,在这种情况下将正确初始化。
struct D1 : B1 {
        using B1::B1;   // implicitly declares D1(int)
        int x{0};   // note: x is initialized
    };

    void test()
    {
        D1 d(6);    // d.x is zero
    }