首页 > 解决方案 > 明确定义方法后出现“标识符未定义”错误

问题描述

我编写了以下代码,由 Item 和 Integer 两个类组成。Integer 是从 Item 派生的,具有值“data”。我编写了一个 printAll 方法,该方法旨在逐个打印包含指针的数组的元素,但是当我尝试在 main 函数中实现 printAll 方法时,我收到一个错误,说它是未定义的,即使我使用 print 定义了它上面的 Integer 类中的方法。

#include <iostream>
#include<string>
using namespace std;

class Item
{
public:
    // prints data
    virtual void print() = 0;

    // returns “INTEGER”
    virtual string getType() = 0;

    // Adds or concatenates the 2 data members. 
    // Throws an exception in case of a type mismacth 
    virtual Item* add(Item* item) = 0;
};

class Integer : public Item {
private:
    int data;

public:
    Integer(int i) {    //Constructor
        data = i;
    }

    void print() {
        cout << "Integer value is: " << data << endl;
    }

    string getType() {
        return "INTEGER";
    }

    Item* add(Item* item) {
        if (item->getType() == "INTEGER") {
            dynamic_cast<Integer*>(item)->data;
        }

        else {
            throw "Type Mismatch";
        }
    }

    void printAll(Item** items, int n) {
        for (int i = 0; i < n; i++) {
            items[i]->print();
        }
    }
};

void main()
{
    int n = 10;
    Item** integers = new Item * [n];
    Item** strings = new Item * [n];

    // populate lists
    for (int i = 0; i < n; i++)
    {
        integers[i] = new Integer(i);
    }

        printAll(integers, n);      // print integers   

标签: c++

解决方案


错误是你上课printAll了。Integer像这样更改您的代码

class Integer : public Item {
    ...
};

void printAll(Item** items, int n) {
    for (int i = 0; i < n; i++) {
        items[i]->print();
    }
}

如果一个方法在一个类中,那么您必须(显式或隐式)提供一个对象来调用该方法。你没有这样做,这就是你得到错误的原因。但在这种情况下printAll,它不应该在任何类中,它应该只是一个可以在不提供对象的情况下调用的常规函数​​。


推荐阅读