c++ - 明确定义方法后出现“标识符未定义”错误
问题描述
我编写了以下代码,由 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
解决方案
错误是你上课printAll
了。Integer
像这样更改您的代码
class Integer : public Item {
...
};
void printAll(Item** items, int n) {
for (int i = 0; i < n; i++) {
items[i]->print();
}
}
如果一个方法在一个类中,那么您必须(显式或隐式)提供一个对象来调用该方法。你没有这样做,这就是你得到错误的原因。但在这种情况下printAll
,它不应该在任何类中,它应该只是一个可以在不提供对象的情况下调用的常规函数。
推荐阅读
- html - 为什么使用 flutter_html 包在我的 Flutter 应用程序中没有显示和html 元素?
- c# - 如何将 Magick.NET LosslessCompress 与 Stream 和 IFormFile 一起使用
- neo4j - 将具有不同标签的节点合并为具有两个标签的新节点
- c++ - Xcode 10.2 中的新 C++ 项目未构建
- c++ - 这个嵌套结构声明是什么意思?
- android - 影子 PackageParser.call ParsePackage PackageParser$Packageparserexception
- markers - 如何获得 SSML来自 Google Cloud 文本转语音 API 的时间戳
- python - 在 Celery python 中使用多个后端
- mysql - MySQL 转储还原不会为仅包含 1 行的表还原数据
- ruby-on-rails - 在 Rspec 和 FactoryBot 期间出错未定义的常量和冻结的数组