在另一个成员函数中调用纯virtual 函数根本不成问题。 (不幸的是,OP 没有复制/粘贴确切的错误消息。)
不幸的是,公开的 OP 样本存在大量拼写错误、语法错误和其他弱点。
解决这个问题后,我发现了一个基本问题:Parent::getFunc() 的 const-ness。
Parent::getFunc() 调用一个非常量成员函数并 改变编译器不接受的成员变量this->var。
删除const,它起作用了。
固定样本:
#include <iostream>
#include <string>
class Parent{
public:
Parent() = default;
virtual std::string func() = 0; // PURE VIRTUAL
std::string getFunc() // WRONG: const
{
return var = func();
}
protected:
std::string var;
};
class Child: public Parent {
public:
Child() = default;
virtual std::string func() override
{
std::string random; // this is very generic I actually pretend
//to do some math here and return a string
return random;
}
};
#define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__
int main()
{
DEBUG(Child child);
DEBUG(child.getFunc());
}
输出:
Child child;
child.getFunc();
Live Demo on coliru
虽然,const 访问器(我称之为“getter”)似乎是合理的。再设计一点点,也可以实现:
#include <iostream>
#include <string>
class Parent{
public:
Parent() = default;
virtual std::string func() const = 0; // PURE VIRTUAL
std::string getFunc() const
{
return var = func();
}
protected:
mutable std::string var;
};
class Child: public Parent {
public:
Child() = default;
virtual std::string func() const override
{
std::string random; // this is very generic I actually pretend
//to do some math here and return a string
return random;
}
};
#define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__
int main()
{
DEBUG(Child child);
DEBUG(child.getFunc());
}
输出:同上
Live Demo on coliru
注意:
我创建了 virtual func() const 以使其可用于 const 实例/成员函数。
成员变量变为mutable,使其在const成员函数中可写。
我必须承认,我个人觉得mutable 有点吓人。在我简单的想法中,有些东西是const,或者不是。然而,mutable 似乎只是为了更新实际const 对象的内部缓存而发明的。因此,它可能是这里的正确工具。 (如果没有更多上下文,这有点难以说。)
更多关于mutable:mutable specifier