假设以下布局:
class Base
{
protected:
Base(P1 p1, P2 p2, P3 p3);
public:
virtual void SomeMethod() = 0;
}
class Derived : public Base
{
public:
using Base::Base;
public:
virtual void SomeMethod() override;
};
Run Code Online (Sandbox Code Playgroud)
我应该能够在Derived这里指定公共构造函数吗?VC++给出以下错误:
无法访问类'Derived'中声明的受保护成员
编译器已在此处生成'Derived :: Derived'[指向使用Base :: Base行]
请参阅'Derived'的声明
即它忽略了继承构造函数上方的访问修饰符.
这是该功能的限制吗?Base对于具有公共构造函数的类没有任何意义,因为它永远不能直接实例化(由于纯虚方法).
我正在尝试为派生类创建一个工厂.我只希望工厂能够创建派生类的实例,所以我已经创建了基础构造函数protected; 派生类只使用基类构造函数,因此它们的构造函数protected也是如此.
我试图将工厂声明为基类的朋友,以便它可以访问protected构造函数.当我使用此命令编译时
clang++ -std=c++11 -stdlib=libc++ Friends.cpp -o Friends
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
Friends.cpp:23:20: error: calling a protected constructor of class 'A'
return new T(i);
^
Friends.cpp:42:16: note: in instantiation of function template specialization 'Create<A>' requested
here
A* a = Create<A>(1);
^
Friends.cpp:30:25: note: declared protected here
using Base::Base;
^
Run Code Online (Sandbox Code Playgroud)
与派生类的类似错误一起B.
我从stackoverflow.com上读到其他问题的感觉,这在C++ 11中是不可能的,但我不确定为什么.有人可以解释为什么这不起作用,或许可以替代?
示例代码
#include <iostream>
using namespace std;
// Forward declaration
template<class T> T* Create(int i);
class Base {
public:
template<class T>
friend T* …Run Code Online (Sandbox Code Playgroud)