从指针库向量中导出类的C ++初始化和函数

时间:2016-05-11 12:12:17

标签: c++

我有一个问题,我有两个类,Word和Noun。名词源自Word。

所有单词和名词都要存储在一个向量中,这就是为什么我要求它在指针中。

问题是我似乎无法从派生类中初始化或调用函数。 我可以推迟一个新词而不是一个名词。

package test;

public class Example {
    public static void testMethod() {
        System.out.println("method executed");
    }
}

它带有1个未解析的外部符号。

2 个答案:

答案 0 :(得分:0)

这段代码有太多问题,所以请允许我提供一个正确,完整的重写来实现你的意思:

#include <iostream>
#include <memory>   // for std::unique_ptr
#include <string>
#include <vector>

class Word
{
private:
    std::string wordName, def, type;

public:
    virtual ~Word() = default;

    Word(std::string w, std::string d, std::string t)
    : wordName(std::move(w))
    , def(std::move(d))
    , type(std::move(t)) {}

    void printWord() const { std::cout << wordName << '\n'; }

    void printDef() { std::cout << def << '\n'; }

    void printType() const { std::cout << type << '\n'; }
};

class Noun : public Word
{
public:
    using Word::Word;
};

int main()
{
    std::vector<std::unique_ptr<Word>> wordVector;

    for (int i = 0; i != 2; ++i)
    {
        std::string w, d, t;
        if (!(std::cin >> w >> d >> t))
        {
            std::cerr << "Failed to read input!\n";
            continue;
        }

        wordVector.push_back(std::make_unique<Noun>(
            std::move(w), std::move(d), std::move(t)));
    }

    for (const auto& wp : wordVector)
    {
        wp->printWord();
        wp->printDef();
        wp->printType();
    }
}

我纠正了一组完全未分类且不完整的问题:

  • 内存管理(std::unique_ptr
  • 通过基础删除的虚拟析构函数
  • 没有荒谬的默认构造函数
  • 继承构造函数而不是手动转发
  • 正确命名的成员函数
  • Const正确性
  • 没有多余的分号
  • 没有多余的std::endl
  • 不是abusing namespace std
  • 基于范围的for循环
  • I / O错误处理
  • 初始化而不是分配
  • 启用移动优化
  • 没有原始new
  • 更正私有成员的访问级别(通过成员函数公开)

答案 1 :(得分:0)

我认为您忘记初始化superclass constructor 在您的Noun课程中试试这个

class Noun : public Word{
public:
    Noun();
    Noun(string wordName, string type, string def): Word(wordName, type, def){};
};

我已经测试过它并且有效。

你的主要()也有一个轻微的修改。只是一点点。所以我可以看到它要求的输入。

int main(){
    vector <Word*> wordVector;
    for (int i = 0; i < 2; i++)
    {

        string wordName, def, type;
        cout<< "entere name";
        cin >> wordName;
        cout<< "entere def";
        cin >> def;
        cout<< "entere type";
        cin >> type;
        cout << endl;
        wordVector.push_back(new Noun(wordName, def, type));    //new Word(wordName, def, type) works
    }
    for (int i = 0; i < 2; i++)
    {
        wordVector[i]->getWord();       //how do you call the function from Noun?
        wordVector[i]->getDef();
        wordVector[i]->getType();
    }
    system("pause");
    return 0;
}