私有继承和隐式转换

SPM*_*PMP 7 c++ inheritance casting

我有一个私有继承的类std::string,并添加了一些函数.我希望能够像使用这个类一样std::string,所以我试图定义一个隐式转换运算符(operator string()).但是,我一直在收到inaccessible base错误.

#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";
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

trial.cpp: In function ‘int main()’:
trial.cpp:15:13: error: ‘std::basic_string<char>’ is an inaccessible base of ‘Test’
 if(t == "hello") {
         ^
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 定义这样的转换是不是一个坏主意?这会破坏任何推荐的编程实践吗?
  2. 我怎样才能做到这一点?

编辑:Clang更有帮助

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 {
       ^~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

0x4*_*2D2 5

到私有基类的转换函数违背了私有继承的目的。这就是标准禁止这种行为的部分原因:

转换函数永远不会用于将(可能是 cv 限定的)对象转换为(可能是 cv 限定的)相同对象类型(或对其的引用),转换为该类型的(可能是 cv 限定的)基类(或对它的引用)或 (可能是简历限定的) void

如果您想访问基类,您应该将继承公开。这使得代码对于可能需要维护代码的其他人来说具有可读性和综合性。