arn*_*rne 6 c++ gcc visibility copy-constructor
我有一个类(让我们base暂时调用它)具有受保护的接口,包括受保护的构造函数等.base返回base值的实例的一些函数:
class base {
protected:
base() {}
base (base const &other) {} // line 6
base foo () {
base ret;
return ret;
}
};
Run Code Online (Sandbox Code Playgroud)
这些函数包装在派生类中,以返回派生类型,如下所示:
class derived : public base {
private:
derived(base const &b) : base(b) {}
public:
derived() : base() {}
derived foo() {
derived d(base::foo()); // line 21
return d;
}
};
Run Code Online (Sandbox Code Playgroud)
为了便于从base返回类型转换为derived返回类型,我提供了一个私有构造函数derived来处理它.
使用gcc 4.1.2在Centos 5.8上进行编译会产生以下错误:
test.cpp: In member function ‘derived derived::foo()’:
test.cpp:6: error: ‘base::base(const base&)’ is protected
test.cpp:21: error: within this context
Run Code Online (Sandbox Code Playgroud)
使用Linux Mint 12上的gcc 4.6.1和clang 2.9,代码编译文件-Wall -Wextra,除了unused parameter对base复制构造函数的警告之外.
我认为这可能是gcc 4.1.2中的编译器错误,但我无法在网上找到任何内容.谁看过这个吗?
没有大的痛苦,我无法更新编译器.除了使基类的复制构造函数公开之外,还有一个简单的解决方法吗?
编辑我base b;在第21行之前添加了derived::foo().在这种情况下,gcc 4.6.1和gcc 4.1.2抱怨默认的ctor base是受保护的,clang 2.9编译时没有警告.这就是DavidRodríguez - dribeas在他的评论中所说的 - 默认的ctor不能在不同的实例上调用base.
编辑2这里似乎适用的标准段落是11.5 [class.protected].gcc 4.1.2似乎是正确的拒绝我的代码不正确,我想知道为什么gcc 4.6.1和clang允许它.请参阅我自己的答案以获得初步解决方案
我的初步解决方案是 makebase的 copyctor public。要禁止derived使用 的复制构造函数复制实例base,继承需要protected改为public。现在生成的类如下所示:
class base {
protected:
base() {}
public:
base (base const &other) {}
protected:
base foo () {
base ret;
return ret;
}
};
class derived : protected base {
private:
derived(base const &b) : base(b) {}
public:
derived() : base() {}
derived foo() {
derived d(base::foo());
return d;
}
};
Run Code Online (Sandbox Code Playgroud)