【问题标题】:Create a class run at main() get undefined reference to... error [duplicate]创建一个在 main() 运行的类获取未定义的引用...错误 [重复]
【发布时间】:2022-01-13 04:14:37
【问题描述】:

arrayADT.h

 #include <iostream>
    using namespace std;
    
    
    template <class T>
    class arrayADT
    {
    private:
        T *A;
        static int size;
        static int length;
    public:
        arrayADT(){
            size=10;
            A= new T[size];      
            length=0;
        }
    
        void increaseSize(){
            T *p;
            size=size*2;
            p= new T[size];
            delete[] A;
            A=p;
            p=NULL;
        }
    
        int getSize(){
            return size;
        }
    
        ~arrayADT();};

example.cpp

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

int main(int argc, char const *argv[])
{   
    arrayADT<int> s;
    s.increaseSize();
    s.getSize();
    return 0;
}

得到错误:

对 `arrayADT::~arrayADT()' 的未定义引用

对 `arrayADT::~arrayADT()' 的未定义引用

对 `arrayADT::length' 的未定义引用

对 `arrayADT::size' 的未定义引用

谁能帮帮我?非常感谢!

【问题讨论】:

  • 请准确描述您是如何编译程序的。

标签: c++ class


【解决方案1】:

我发现了两个不同的问题:

  1. 析构方法必须有一个{}的范围,即使它是空的。
  2. 我删除了 static 关键字,因为每个对象都将具有 sizelength 属性。
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;
    
template<class T>
class arrayADT
{
    private:
        T *A;
        int size;    /* Removed the static keyword used in data members. */
        int length;  /* Removed the static keyword used in data members. */
        
    public:
        arrayADT()
        {
            size = 10;
            A = new T[size];      
            length = 0;
        }
        
        ~arrayADT(){} /* The destruction method has been edited. */
        
        void increaseSize()
        {
            T *p;
            size = size * 2;
            p = new T[size];
            delete[] A;
            A = p;
            p = NULL;
        }
    
        int getSize()
        {
            return size;
        } 
};

int main(int argc, char const *argv[])
{   
    arrayADT<int> s;
    s.increaseSize();
    cout << s.getSize() << endl;
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多