gpt4 book ai didi

c++ - 私有(private)继承和隐式转换

转载 作者:可可西里 更新时间:2023-11-01 18:31:13 25 4
gpt4 key购买 nike

我有一个从std::string 私有(private)继承的类,并添加了一些函数。我希望能够像 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") {
^

问题:

  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 {
^~~~~~~~~~~~~~

最佳答案

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

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.

如果你想访问基类,你应该公开继承。这使代码对于可能需要维护它的其他人来说是可读的和全面的。

关于c++ - 私有(private)继承和隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35805951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com