私は個人的に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") {
^
質問:それはこのような変換を定義することは悪い考え
- ですか?推奨されているプログラミングの慣行が破られるか?
- どのように私はこの作業を行うことができますか?
EDIT:クランはい、それのために設計されていないクラスを継承することは一般的に悪い考えです
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ではありません。 –
私はそれを動作させることができると思う方法の1つは、公開継承を使用し、派生クラスを '' final''にすることです。私は派生クラスに割り当てられた追加メモリを持っていないので、呼び出されていないデストラクタは問題にならないはずです。 – SPMP