#include <iostream>
#include "memory"
// base class
class base
{
public:
void setVal(int val)
{
m_val = val;
}
int getVal()
{
std::cout << "val = " <<m_val<<std::endl;
return m_val;
}
bool checkVal(int val)
{
return val>8?true : false;
}
private:
int m_val = 5;
};
// derived class
class derived1: public base
{
private:
};
// derived class
class derived2: public base
{
public:
bool checkd2Val()
{
checkVal(9);
}
private:
};
int main()
{
std::unique_ptr<base> d1;
d1 = std::make_unique<derived1>();
std::unique_ptr<base> d2;
d2 = std::make_unique<derived2>();
d2->checkd2Val(7);
return 0;
}
编译器给出错误:
No member named "checkd2Val" in base.
我想知道在这种情况下我们如何调用 checkd2Val ?谢谢!!
错误是正确的。 您尝试使用
checkd2Val()
指针调用 base*
,而 checkd2Val()
中不存在 base
。
如果您确实需要从
checkd2Val()
调用 d2
那么您需要对其进行类型转换:
static_cast<derived2*>(d2.get())->checkd2Val(7);
否则,您应该将
base::checkVal()
声明为 virtual
并让 derived2
覆盖它。