相关疑难解决方法(0)

为什么在虚拟继承中调用Default构造函数?

我不明白为什么在下面的代码中,当我实例化一个类型的对象时daughter,默认的grandmother()构造函数被调用?

我认为grandmother(int)应该调用构造函数(遵循我的mother类构造函数的规范),或者由于虚拟继承,这个代码根本不应该编译.

这里编译器grandmother在我的后面静默调用默认构造函数,而我从来没有要求它.

#include <iostream>

class grandmother {
public:
    grandmother() {
        std::cout << "grandmother (default)" << std::endl;
    }
    grandmother(int attr) {
        std::cout << "grandmother: " << attr << std::endl;
    }
};

class mother: virtual public grandmother {
public:
    mother(int attr) : grandmother(attr) {
        std::cout << "mother: " << attr << std::endl;
    }
};

class daughter: virtual public mother {
public:
    daughter(int attr) : mother(attr) {
        std::cout << "daughter: " << …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance virtual-inheritance

73
推荐指数
1
解决办法
1万
查看次数

使用gcc接受的"noexcept"构造函数的程序,被clang拒绝

代码:

struct T { T() {} };

struct S
{
    T t;

    S() noexcept = default;
};

int main()
{
//    S s;
}
Run Code Online (Sandbox Code Playgroud)

g ++ 4.9.2接受此但没有错误或警告,但第7行的clang 3.6和3.7报告:

error: exception specification of explicitly defaulted default constructor does not match the calculated one
Run Code Online (Sandbox Code Playgroud)

但是,如果该行S s;未被注释掉,g ++ 4.9.2现在报告:

noex.cc: In function 'int main()':
noex.cc:12:7: error: use of deleted function 'S::S()'
     S s;
       ^
noex.cc:7:5: note: 'S::S() noexcept' is implicitly deleted because its  exception-specification does not match the implicit exception-specification '' …
Run Code Online (Sandbox Code Playgroud)

c++ gcc clang noexcept c++11

15
推荐指数
1
解决办法
3749
查看次数

标签 统计

c++ ×2

c++11 ×1

clang ×1

gcc ×1

inheritance ×1

noexcept ×1

virtual-inheritance ×1