C++ 访问器函数可以调用纯虚拟函数吗?
如果我的纯虚函数是,即C++ 访问器函数可以调用纯虚拟函数吗?,c++,virtual,C++,Virtual,如果我的纯虚函数是,即 virtual string func()=0; 它是否可以返回到访问器函数 编辑:我为之前的混淆道歉,所以我添加了一个示例代码 class Parent{ public: parent(void){}; virtual string func()=0; string getFunc (void) const{return var=func();} ; protected: string var; } class Child: publ
virtual string func()=0;
它是否可以返回到访问器函数
编辑:我为之前的混淆道歉,所以我添加了一个示例代码
class Parent{
public:
parent(void){};
virtual string func()=0;
string getFunc (void) const{return var=func();} ;
protected:
string var;
}
class Child: public Parent{
public:
class Child(void);
string func(){
string random // this is very generic I actually pretend
//to do some math here and return a string
return random};
我的意图是使用实例化的子对象并要求accessorgetFunc返回一个值,我只能基于func计算该值。但是错误表明虚拟函数的本质不允许返回,坦白地说,我觉得这很奇怪,因为它确实有返回标签。在另一个成员函数中调用纯虚拟函数应该一点问题都没有。不幸的是,OP没有复制/粘贴准确的错误消息
不幸的是,OP的公开示例有很多打字错误、语法错误和其他弱点
解决了这个问题,我发现了一个基本问题:Parent::getFunc的常量
getFunc调用一个非常量成员函数,并对编译器不接受的成员变量this->var进行变异
除去常数,它就工作了
固定样本:
#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());
}
尽管如此,我称之为“getter”的const访问器似乎是合理的。再进行一点重新设计,也可以实现:
#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());
}
输出:同上
注:
我创建了虚拟func-const,以使其可供const实例/成员函数访问
成员变量变为可变的,以使其在常量成员函数中可写
我必须承认,我个人觉得这种变化有点吓人。在我简单的头脑中,有些东西是常量或不是常量。然而,可变表似乎只是为了更新实际常量对象的内部缓存而发明的。因此,它可能是正确的工具。没有更多的上下文,这有点难说
关于可变的更多信息:对不起,您所说的访问器函数是什么意思?您是指字符串getFrobaz{return func;}当您尝试它时发生了什么事?@user207421否,但这意味着问题可能应该解释或澄清它是什么。@bolov解释一个访问器函数?真正地这个词到处都用。访问器和变异器当然不是在这种情况下。只有在实际对象是派生类的情况下才不会有问题,如您的示例中所示,这不是OP所要求的。@user207421抱歉,您能详细说明一下吗?@user207421在OPs示例中,类子级是从类父级派生的。否则,虚拟方法就没有多大意义。我监督过什么吗?