首页 > 解决方案 > 为什么我的类函数在 main 中“未定义”我在代码中遗漏了什么?

问题描述

类中的函数本身工作得很好,错误似乎有点奇怪,我不明白问题出在哪里。类头//太长

#include <iostream>
using namespace std;
struct Node
{
    int value;
    Node* left;
    Node* right;
};
class BinarySearchTree
{
private:
    int isIdentical;
    int sum;
    int sum1;
    int sum2;
public:
    bool checkBSTidentical(Node* x, Node* y);
    int BSTidentical(Node* firstTree, Node* secondTree);
    int BSTnotIdentical(Node* firstTree, Node* secondTree);
    int BSTsum(Node* x);
    int compareBST(Node* root1, Node* root2);
    Node* build(int data);
    Node* insert(Node* node, int Value);
    void in(Node* root);
};

CPP 类 // 太长

Main //虽然我声明了类,但所有类函数都没有定义

#include <iostream>
#include "BinarySearchTree.h"
using namespace std;
int main()
{
    Node* tree1 = NULL;
    Node* tree2 = NULL;
    int x;
    tree1 = insert(tree1, 50); 
    tree1 = insert(tree1, 40);
    tree1 = insert(tree1, 30);
    tree1 = insert(tree1, 20);
    tree1 = insert(tree1, 10);
    cout << "Binary Tree 1: " << endl;
    in(tree1);
    cout << endl;
    tree2 = insert(tree2, 50);
    tree2 = insert(tree2, 40);
    tree2 = insert(tree2, 30);
    tree2 = insert(tree2, 20);
    tree2 = insert(tree2, 10);
    cout << "Binary Tree 2: " << endl;
    in(tree2);
    cout << endl;
    x = compareBST(tree1, tree2);
    cout << "Result: " << x << endl;
    return 0;
}

标签: c++

解决方案


insert(), in(), compareBST(), 这些都是BinarySearchTree类的非静态方法,但你main()试图调用它们,就好像它们是独立函数一样。这就是您收到“未找到标识符”错误的原因。您需要在 的对象实例上调用它们BinarySearchTree,例如:

#include <iostream>
#include "BinarySearchTree.h"
using namespace std;

int main()
{
    BinarySearchTree bsTree;
    Node* tree1 = NULL;
    Node* tree2 = NULL;
    int x;
    tree1 = bsTree.insert(tree1, 50); 
    tree1 = bsTree.insert(tree1, 40);
    tree1 = bsTree.insert(tree1, 30);
    tree1 = bsTree.insert(tree1, 20);
    tree1 = bsTree.insert(tree1, 10);
    cout << "Binary Tree 1: " << endl;
    bsTree.in(tree1);
    cout << endl;
    tree2 = bsTree.insert(tree2, 50);
    tree2 = bsTree.insert(tree2, 40);
    tree2 = bsTree.insert(tree2, 30);
    tree2 = bsTree.insert(tree2, 20);
    tree2 = bsTree.insert(tree2, 10);
    cout << "Binary Tree 2: " << endl;
    bsTree.in(tree2);
    cout << endl;
    x = bsTree.compareBST(tree1, tree2);
    cout << "Result: " << x << endl;
    return 0;
}

推荐阅读