C++ 从派生类调用的抽象基类成员函数
我仍然试图掌握抽象基类的概念,以及从派生类可以做什么和不能做什么 我有以下代码:C++ 从派生类调用的抽象基类成员函数,c++,inheritance,abstract-class,C++,Inheritance,Abstract Class,我仍然试图掌握抽象基类的概念,以及从派生类可以做什么和不能做什么 我有以下代码: class NpBaseTest { ... friend std::ostream& operator<<(std::ostream &os, const NpBaseTest& p_npBaseTest); /* Implemented in the .cpp file as - std::ostream& operator<&l
class NpBaseTest {
...
friend std::ostream& operator<<(std::ostream &os, const NpBaseTest& p_npBaseTest);
/* Implemented in the .cpp file as -
std::ostream& operator<<(std::ostream &os, const NpBaseTest& p_npBaseTest)
{
p_npBaseTest.show(os);
return os;
}
*/
virtual uint16_t process(int) const = 0;
virtual void show(std::ostream& os) const
{
os
<< "Test ID [" << get_test_id() << "] "
<< "Module Type [" << get_module_type() << "]" << std::endl;
}
};
class CavTest : public NpBaseTest
{
...
friend std::ostream& operator<<(std::ostream &os, const CavTest& p_cavtest);
/* Implemented in the .cpp file as
std::ostream& operator<<(std::ostream &os, const CavTest& p_cavtest)
{
p_cavtest.show(os);
return os;
}
*/
uint16_t process(int p_val) const
{
//...implemented here
}
void show(std::ostream& os) const
{
NpBaseTest::show(os);
os
<< "CavTest Type" << std::endl;
}
};
在派生类中
void CavTest::show_all(std::ostream& os) const
{
os
<< "CavTest Type" << std::endl;
}
void cavetest::show_all(std::ostream&os)const
{
操作系统
如图所示,您当前的问题与抽象(又称纯虚拟)方法无关,因为这些方法都不涉及
问题1:成员函数声明语法
基类show()
有一个额外的NpBaseTest::
限定符,该限定符不应存在。只有在类声明之外定义成员函数时,才需要该额外限定符。通常情况下:
// Foo.hpp
class Foo
{
void bar();
}
// Foo.cpp
#include "Foo.hpp"
void Foo::bar()
{
// ...
}
这是您显示错误消息的最可能原因
问题2:可见性
基类show()
是私有的,因为在类中,默认的可见性是private
。不能从派生类调用私有基类方法,即调用NpBaseTest::show()
,尽管语法正确,但不会编译
问题3:类声明语法
两个类声明在右大括号后都缺少一个
要编译此文件,最基本的更改是:
class NpBaseTest
{
protected: // or: public:
virtual void show(std::ostream& os) const { /*...*/ }
};
class CavTest : public NpBaseTest
{
// private by default
// Works because you can override with a lower visibility,
// but not with a higher one.
void show(std::ostream& os) const override
{
NpBaseTest::show(os);
// ...
}
};
覆盖
是可选的,但如果您使用的是具有C++11功能的(即非古代版本),则强烈建议使用编译器。请将您的程序缩减到演示错误的尽可能小的完整程序。请将您的问题复制并将整个简短程序粘贴到您的问题中。请将所有错误消息复制粘贴到您的问题中。有关详细信息,请参阅。请尝试this->NpBaseTest::show(os);
。但它实际上应该根据您显示的内容进行编译。@MooingDuck正如我所说的,在声明中,class::函数不是必需的,因为实现已经在类声明中了-我不是指函数call@ImNot出于好奇:您使用的是哪种编译器?正如前面提到的this->
应该是imp继承的虚拟函数重写的合法性。是的。这已经造成了很多次混乱(至少对我来说)。我习惯于相信缩进,但从这里开始,我绝对不应该依赖它。叹气。
class NpBaseTest
{
protected: // or: public:
virtual void show(std::ostream& os) const { /*...*/ }
};
class CavTest : public NpBaseTest
{
// private by default
// Works because you can override with a lower visibility,
// but not with a higher one.
void show(std::ostream& os) const override
{
NpBaseTest::show(os);
// ...
}
};