nSv*_*v23 7 c++ inheritance class c++11
我有2类Training和Testing,其中Training是基类和Testing是的派生类Training。
我有Testing类成员函数,float totalProb(Training& classProb, Training& total),它有 2 个参数,都是Training类对象。编码:
void Testing::totalProb(Training& classProb, Training& total) {
_prob = (_prob * ((float)(classProb._nOfClass) / total._tnClass));
cout << "The probalility of the " << it->first << " beloning to " << classProb._classType << " is: " << _prob << endl;
}
Run Code Online (Sandbox Code Playgroud)
基本上这个函数的作用是计算test1(Testing类对象)中每个文档属于class1(类对象)的概率Training。
所有Training类(即基类)变量Protected和所有Training类函数都是Public.
当我尝试运行时test1.totalProb(class1, total);出现错误Error C2248 'Training::_probCalc': cannot access protected member declared in class 'Training'。我无法解决这个问题。
您正在尝试访问您的母类的另一个实例的成员:
classProb,但继承使您只能访问您自己的父类的受保护成员。
一种纠正方法(但它很大程度上取决于您要做什么)是_probClass在您的 Training 类中放置一个 getter并在您的测试中调用它,例如对于 _probCalc 成员:
public:
(Type) Training::getProbCalc() {
return _probCalc;
}
Run Code Online (Sandbox Code Playgroud)
更改循环中的呼叫:
for (it3 = classProb.getProbCalc().begin(); it3 != classProb.getProbCalc().end(); it3++)
Run Code Online (Sandbox Code Playgroud)
如果您尝试访问由您的母实例继承的您自己的成员,只需直接调用它们即可。例如:
for (it3 = _probCalc().begin(); it3 != _probCalc().end(); it3++)
Run Code Online (Sandbox Code Playgroud)