私有继承和隐式转换 [英] Private inheritance and implicit conversion
问题描述
我有一个从 std :: string
私下继承的类,并添加了一些函数。我希望能够像 std :: string
一样使用这个类,所以我试图定义一个隐式转换运算符( operator string()
)。但是,我不断收到无法访问的基础
错误。
I have a class that inherits privately from std::string
, and adds some functions. I want to be able to use this class just like std::string
, so I am trying to define an implicit conversion operator (operator string()
). However, I keep getting inaccessible base
error.
#include <iostream>
#include <string>
using namespace std;
class Test:private string {
int _a;
public:
operator string() {
return "hello";
}
};
int main() {
Test t;
if(t == "hello") {
cout<<"world\n";
}
}
错误:
trial.cpp: In function ‘int main()’:
trial.cpp:15:13: error: ‘std::basic_string<char>’ is an inaccessible base of ‘Test’
if(t == "hello") {
^
问题:
- 定义这样的转换是不是一个坏主意?这会破坏任何推荐的编程习惯吗?
- 我该如何使用?
编辑:Clang更有帮助
Clang was more helpful
trial.cpp:8:5: warning: conversion function converting 'Test' to its base class 'std::basic_string<char>' will never be used
operator string() {
^
trial.cpp:15:8: error: cannot cast 'Test' to its private base class 'basic_string<char, std::char_traits<char>, std::allocator<char> >'
if(t == "hello") {
^
trial.cpp:5:12: note: declared private here
class Test:private string {
^~~~~~~~~~~~~~
推荐答案
私有基类的转换函数违背了私有继承的目的。这就是为什么标准禁止这种行为的部分原因:
A conversion function to a private base class defeats the purpose of private inheritance. That's part of the reason why the standard forbids this kind of behavior:
转换函数从不用于转换(可能是cv-qualified) )将
对象(可能是cv限定的)相同的对象类型(或对它的引用),到该类型的(可能是cv限定的)基类(或对它的引用),或者(可能是cv-qualified)void
。
A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified)
void
.
如果如果要访问基类,则应将继承公开。这使代码可以保持可读性和全面性,以便其他人可能需要维护它。
If you want access to the base class you should make the inheritance public. This keeps the code readable and comprehensive for others who may have to maintain it.
这篇关于私有继承和隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!