[英]C++ class inheritance and member functions
所有,我很難理解為什么會出現以下錯誤。 我 promise 這不是作業問題,但我是 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(); }
I don't understand why the member function get_label() wasn't inherited from the Base class to the Derived class, such that I'm not able to access it via the VecDerived class. 有沒有辦法可以解決這個問題? 在此先感謝您的幫助!
Visual Studio 發出一條錯誤消息,為您提供更多提示:
錯誤 C2247:“Base::get_label”不可訪問,因為“Derived”使用“private”從“Base”繼承
因此,如果您想通過Derived
的 object 訪問Base::get_label
,那么您需要將基礎 class 公開:
class Derived : public Base
或公開get_label
:
class Derived : private Base {
public:
using Base::get_label;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.