首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要帮助来填补空白吗?

需要帮助来填补空白吗?
EN

Stack Overflow用户
提问于 2022-09-09 04:23:45
回答 1查看 73关注 0票数 -4

我已经填补了空白行(line1,line2 line3),但是我没有得到任何输出。

注意-只需要编辑这三行

密码-

代码语言:javascript
复制
#include <iostream>
#include <cstring>

using namespace std;

class Base
{
protected:
    string s;

public:
    Base(string c) : s(c) {}

    virtual ~Base() {}   // line 1

    virtual string fun(string a) = 0; // line 2 
};

class Derived : public Base
{
public:
    Derived(string c) : Base(c) {}
    ~Derived();
    string fun(string x)
    {
        return s + x;
    }
};
class Wrapper
{
public:
    void fun(string a, string b)
    {
        Base *t = (Base *) &a; // LINE-3
        string i = t->fun(b);
        cout << i << " ";
        delete t;
    }
};

Derived::~Derived() { cout << s << " "; }

int main()
{
    string i, j;
    cin >> i >> j;
    Wrapper w;
    w.fun(i, j);

    return 0;
}

更多详情及输入/输出-

代码语言:javascript
复制
input - o k 
expected output - ok o

input - c ++
expected output - c++ c

关于这些问题的细节我不知道在这里写什么,所以请原谅没有写它。

EN

回答 1

Stack Overflow用户

发布于 2022-09-09 06:17:11

这是一个难题,它教会了拼凑编码的糟糕实践。

第3行应该包含new,因为后面的代码中存在delete t;。不管创建了什么,都有fun方法,但不能是new Base,因为Base是抽象的。因为fun是虚拟的,所以它可以是:

代码语言:javascript
复制
Base *t = new Derived(a);

Derived使用string a进行初始化,并在析构函数中打印它,这与所需的输出相匹配。

PS。没有理由在这里这一行不能是Derived *t = new Derived(a);

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73657317

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档