【问题标题】:Why are my class functions being "undefined" in main am i missing something in the code?为什么我的类函数在 main 中“未定义”我在代码中遗漏了什么?
【发布时间】:2020-04-22 20:08:52
【问题描述】:

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

#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;
}

【问题讨论】:

  • 我尝试添加类本身,但它一直说我不能,因为大部分文本都是代码
  • 您遇到的编译器错误是什么?
  • 插入标识符未找到,所有其他功能都相同
  • 我猜你只编译 main.cpp,而不是 BinarySearchTree.cpp。您需要将两个源文件编译为一个程序(或将两个源文件编译为目标文件,然后将所有目标文件链接到一个程序)。

标签: c++


【解决方案1】:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多