注意派生使用C++ 11统一初始化语法来调用基类构造函数.
class base
{
protected:
base()
{}
};
class derived : public base
{
public:
derived()
: base{} // <-- Note the c++11 curly brace syntax
// using uniform initialization. Change the
// braces to () and it works.
{}
};
int main()
{
derived d1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
g ++ 4.6编译它,但是g ++ 4.7没有:
$ g++-4.7 -std=c++11 -Wall -Wextra -pedantic curly.cpp -o curly
curly.cpp: In constructor ‘derived::derived()’:
curly.cpp:4:13: error: ‘base::base()’ is protected
curly.cpp:19:24: error: within this context …Run Code Online (Sandbox Code Playgroud) 现在,我正在学习C++中的继承功能,并希望测试最近学到的虚拟基类的概念.我尝试了以下简单的代码:
#include <iostream>
using namespace std;
class A
{
private:
int m_value;
string m_caller;
public:
A(int p_value, string p_caller) : m_value{p_value}, m_caller{p_caller}
{
cout<<"Instantiating A via "<<m_caller<<endl;
}
};
class B : virtual public A
{
private:
int m_value;
public:
B(int p_value1,int p_value2) : A{p_value1,"B"}, m_value{p_value2}
{
cout<<"Instantiating B."<<endl;
}
};
class C : public B
{
public:
C(int p_value1,int p_value2) : A{p_value1,"C"}, B(p_value1, p_value2)
{
cout<<"Instantiating C."<<endl;
}
};
int main()
{
C c1(1,2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意B(p_value1, …
c++ inheritance multiple-inheritance virtual-inheritance c++11
继续关于多个(虚拟)继承的这个问题,我想询问一个简单的MWE让g ++ 5.2.0沮丧,而clang ++ 3.6.2处理它就好了,没有任何抱怨,即使有-Wall和-Wextra设置.所以这是MWE:
class Z {};
class A : virtual Z { protected: A() {} };
class B : virtual Z { protected: B() {} };
class C : A, B { public: C() : A{}, B{} {} };
int main() { C c{}; return 0; }
Run Code Online (Sandbox Code Playgroud)
与clang ++不同,g ++抱怨如下:
gccodd.c++: In constructor ‘C::C()’:
gccodd.c++:2:34: error: ‘A::A()’ is protected
class A : virtual Z { protected: A() {} …Run Code Online (Sandbox Code Playgroud) 我有2个基类(B1和B2),它们是从公共基类(B)派生出来的,它们有一个公共变量(let:int x;来自基数B),在第一个基数中x=0,在第二个基数中x=10(默认值在B1中给出, B2构造函数).
视觉:
class B
{
int x;
protected:
B(int x) : x{x}{}
};
class B1 : public B
{
protected:
B1() : B(0){}
};
class B2 : public B
{
protected:
B2() : B(10){}
};
Run Code Online (Sandbox Code Playgroud)
现在,如果我再推导一个类:
class D : virtual public B1, virtual public B2
{
public:
D() : B1{}, B2{}{}
};
Run Code Online (Sandbox Code Playgroud)
这里只有一个x的副本可用于虚拟概念,现在如果我尝试使用派生类对象访问x值,那么x的实例将在O/p(x=0或x=10)中得到,为什么?