相关疑难解决方法(0)

私有继承和隐式转换

我有一个私有继承的类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 …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance casting

7
推荐指数
1
解决办法
960
查看次数

标签 统计

c++ ×1

casting ×1

inheritance ×1