繁体   English   中英

访问器函数可以调用纯虚函数吗?

[英]Can a pure virtual function be called by an accessor function?

如果我的纯虚函数是 ie

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}; 

我的意图是然后使用实例化的子对象并要求访问器(getFunc()) 返回一个值,我只能根据 func() 进行计算。 但是错误指出虚函数的性质不允许返回,坦率地说,我觉得很奇怪,因为它上面确实有返回标签。

在另一个成员函数中调用纯virtual函数根本不应该是问题。 (不幸的是,OP 没有复制/粘贴确切的错误消息。)

不幸的是,公开的 OP 样本有很多拼写错误、语法错误和其他弱点。

解决这个问题后,我发现了一个基本问题: Parent::getFunc()const

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();

在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());
}

输出:同上

在coliru上进行现场演示

笔记:

  1. 我使virtual func() const使其可用于const实例/成员函数。

  2. 成员变量变得mutable以使其在const成员函数中可写。

我必须承认,我个人觉得mutable的有点吓人。 在我看来,有些东西是const或不是。 然而, mutable似乎只是为了更新实际const对象的内部缓存而发明的。 因此,它可能是这里的正确工具。 (如果没有更多上下文,这有点难以说。)

有关mutable更多信息:可变说明符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM