【发布时间】: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