我有一个类从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";
}
}
错误:
trial.cpp: In function ‘int main()’:
trial.cpp:15:13: error: ‘std::basic_string<char>’ is an inaccessible base of ‘Test’
if(t == "hello") {
^
问题:
- 它是一个坏主意来定义这样的转换?这是否违反了推荐的编程习惯?
- 我该如何做这项工作?
编辑:锵更有益
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 {
^~~~~~~~~~~~~~
请在将来发布完整的错误消息。 – AndyG
“hello”不是std :: string。 –
我想我可以使它工作的一种方式是使用公共继承,并使派生类“final”。我没有在派生类中分配任何额外内存,因此不会调用析构函数(?)不应该成为问题。 – SPMP