简体   繁体   中英

why does this code generate an unknown error?

I am trying to add a new Author to a Document but I get an error that resembles this 1 :

undefined reference to 'Document::numberofbjects'

Could you please tell me what this error is and why am I getting it?

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

class Author{
    string name;
public:
    Author(){}
    Author(string n){
       name = n;
    }
    string getname(){
        return name;
    }
};

class Document{
    string title;
    Author *authors;
    static int numberofbjects;
public:
    Document(string t,Author a[],int n){
       title=t;
        authors = a;
        numberofbjects=n;
    }
    void addauthor(Author a1){
        Author *ptr=new Author[numberofbjects+1];
        for(int i=0;i<numberofbjects;i++){ //another question below 
            ptr[i]=authors[i];
        }
        ptr[numberofbjects]=a1;
        authors=ptr;
        numberofbjects++;
    }
    void printAuthors(){
        for(int i=0;i<numberofbjects;i++){
            cout<<authors[i].getname()<<endl;
        }
    }
    
};

int main()
{
    Author a1("Jony");
    Author a2("Jonson");
    Author array[2];
    array[0]=a1;
    array[1]=a2;
    Document D1("ARK",array,2);
    Author a3("Jonthan");
    D1.addauthor(a3);
    D1.printAuthors();
    
    return 0;
}

1 The error has been inferred by the answers and would likely be a linker error

You've declared the static variable Document::numberofbjects but not defined it so the linking phase will fail.

Add this out of the class definition:

int Document::numberofbjects = 0;

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM