Наследование класса C ++ и функции-члены - PullRequest
0 голосов
/ 27 апреля 2020

Все, мне трудно понять, почему я получаю следующую ошибку. Я обещаю, что это не домашнее задание, но я новичок в 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 () не была унаследована от Базовый класс для класса Derived, так что я не могу получить к нему доступ через класс VecDerived. Есть ли способ, которым это может быть решено? Заранее спасибо за помощь!

1 Ответ

1 голос
/ 27 апреля 2020

Visual Studio выдает сообщение об ошибке, которое дает вам больше подсказок:

ошибка C2247: «Base :: get_label» недоступен, поскольку «Derived» использует «private» для наследования от «Base»

Итак, если вы хотите получить доступ к Base::get_label через Derived объект, вам нужно либо сделать базовый класс public c:

class Derived : public Base

, либо сделать get_label publi c:

class Derived : private Base {
public:
    using Base::get_label;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...