派生类函数
class Base
{
protected:
int data;
public:
virtual int getData() { return data; }
virtual void setData(int value) { data = value; }
};
class Child : protected Base
{
public:
void setData(int value)
{
Base::setData(value);
cout << "Data is set.\n";
}
};
class Worker
{
private:
Child obj;
public:
void setGlobalData(int val)
{
obj.setData(val); // This is normal
}
int getGlobalData()
{
return obj.getData(); // Line 140, Error
}
};
使用 Worker 类编译文件时出错:
Base.hpp: In member function ‘int Worker::getGlobalData()’:
Base.hpp:22:19: error: ‘virtual int Base::getData()’ is inaccessible
Worker.cpp:140:34: error: within this context
Worker.cpp:140:34: error: ‘Base’ is not an accessible base of ‘Child’
class Base
{
protected:
int data;
public:
virtual int getData() { return data; }
virtual void setData(int value) { data = value; }
};
class Child : protected Base
{
public:
void setData(int value)
{
Base::setData(value);
cout << "Data is set.\n";
}
};
class Worker
{
private:
Child obj;
public:
void setGlobalData(int val)
{
obj.setData(val); // This is normal
}
int getGlobalData()
{
return obj.getData(); // Line 140, Error
}
};
Error during compiling of file with Worker class:
Base.hpp: In member function ‘int Worker::getGlobalData()’:
Base.hpp:22:19: error: ‘virtual int Base::getData()’ is inaccessible
Worker.cpp:140:34: error: within this context
Worker.cpp:140:34: error: ‘Base’ is not an accessible base of ‘Child’
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(6)
挽清梦2024-10-05 12:02:20
这编译:
class Base
{
protected:
int data;
public:
virtual int getData() {return data;}
virtual void setData(int value) { data = value; }
};
class Child : public Base
{
public:
void setData(int value)
{
Base::setData(value);
cout << "Data is set.\n";
}
};
class Worker
{
private:
Child obj;
public:
void setGlobalData(int val)
{
obj.setData(val); // This is normal
}
int getGlobalData()
{
return obj.getData();
}
};
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您真的将其设为公共基类吗?
否则它是私有的,并且您会收到与您所遇到的类似的错误,即:
Did you actually make it a public base class?
Otherwise it's private, and you get errors similar to what you have, namely: