【问题标题】:C++ class inheritance and member functionsC++ 类继承和成员函数
【发布时间】:2020-04-27 19:36:01
【问题描述】:

所有, 我很难理解为什么会出现以下错误。我保证这不是作业问题,但我是 C++ 新手!这是我的代码:

#include <iostream>
#include <string>
#include <vector>

class Base {
protected:
  std::string label;
public:
  Base(std::string _label) : label(_label) { }
  std::string get_label() { return label; }
};

class Derived : private Base {
private:
  std::string fancylabel;
public:
  Derived(std::string _label, std::string _fancylabel)
   : Base{_label}, fancylabel{_fancylabel} { }
  std::string get_fancylabel() { return fancylabel; }
};

class VecDerived {
private:
  std::vector<Derived> vec_derived;
public:
  VecDerived(int n)
  {
    vec_derived = {};
    for (int i = 0; i < n; ++i) {
      Derived newDerived(std::to_string(i), std::to_string(2*i));
      vec_derived.push_back(newDerived);
    }
  }
  std::string get_label(int n)  { return vec_derived.at(n).get_label(); }
  std::string get_fancylabel(int n) { return vec_derived.at(n).get_fancylabel(); }
};

int main (void)
{
  VecDerived obj(5);
  std::cout << obj.get_label(2) << " " << obj.get_fancylabel(2) << "\n";
  return 0;
}

我得到的编译器错误如下:

test1.cpp: In member function ‘std::__cxx11::string VecDerived::get_label(int)’:
test1.cpp:33:70: error: ‘std::__cxx11::string Base::get_label()’ is inaccessible within this context
   std::string get_label(int n)  { return vec_derived.at(n).get_label(); }
                                                                  ^
test1.cpp:9:15: note: declared here
   std::string get_label() { return label; }
               ^~~~~~~~~
test1.cpp:33:70: error: ‘Base’ is not an accessible base of ‘__gnu_cxx::__alloc_traits<std::allocator<Derived> >::value_type {aka Derived}’
   std::string get_label(int n)  { return vec_derived.at(n).get_label(); }

我不明白为什么成员函数 get_label() 没有从 Base 类继承到 Derived 类,因此我无法通过 VecDerived 类访问它。有没有办法可以解决这个问题?提前感谢您的帮助!

【问题讨论】:

  • 你为什么选择私有继承是你希望继承的东西是公开的?
  • >有没有办法解决这个问题?是的,公共继承
  • 关于作业的问题的问题是它们包含的信息太少,要求其他人编写代码而不付出任何努力,等等。询问家庭作业本身并没有什么坏处

标签: c++ oop inheritance


【解决方案1】:

Visual Studio 发出一条错误消息,为您提供更多提示:

错误 C2247:“Base::get_label”不可访问,因为“Derived”使用“private”从“Base”继承

因此,如果您想通过Derived 对象访问Base::get_label,那么您需要将基类公开:

class Derived : public Base

或将get_label公开:

class Derived : private Base {
public:
    using Base::get_label;

【讨论】:

  • @idclev463035818 谢谢,已修复:)。
  • 好的,我想我明白了。谢谢!
猜你喜欢
  • 2010-09-08
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
  • 2012-04-12
  • 2018-11-22
  • 1970-01-01
相关资源
最近更新 更多