简体   繁体   中英

Undefined reference to Class::Class/Function (Beginner in OOP)

I have this annoying error; Undefined Reference to Shape::Shape(...), Shape::getName(...), Shape::getAge(...)

My Main.cpp is this

#include <iostream>
#include <string>
#include "Bit.h"

using namespace std;

int main()
{
    //simple assignment
    string name;
    int age;
    cout<<"enter name: ";
    cin>>name;
    cout<<"enter age: ";
    cin>>age;

    Shape sh(name,age); //class declaration (i think here is the problem)

    cout<<endl<<"name: "<<sh.getName();
    cout<<endl<<"age: "<<sh.getAge();




    return 0;
}

This is the Bit.h header

#include <iostream>
#include <string>

using namespace std;

#ifndef BIT_H
#define BIT_H

 //creating class
class Shape{
    string newName;
    int newAge;

public:
    //Default Constructor
    Shape();
    //Overload Constructor
    Shape(string n,int a);
    //Destructor
    ~Shape();
    //Accessor Functions
    string getName();
    int getAge();

};

And finally, this is the Bit.cpp

#include "Bit.h"
//constructors and destructor
Shape::Shape(){
    newName="";
    newAge=0;
}

Shape::Shape(string n, int a){
    newName=name;
    newAge=age;
}

Shape::~Shape(){

}

string Shape::getName(){
    return newName;
}
//getters
int Shape::getAge(){
    return newAge;
}

I understand, that this might be a very simple problem/error, but I have been struggling for about 2 hours. I suppose that the error is in the declaration od "sh" object, even if I declare it like this "Shape sh();" or "Shape sh;", there are still errors. Thanks

EDIT. GNU GCC Compiler EDIT2. Using Code Blocks (sorry for forgetting all these)

You're probably not compiling Bit.cpp , but only Main.cpp .

Considering that Bit.h , Bit.cpp and Main.cpp are in the same folder, here is how you should compile it :

g++ *.cpp

It will still not compile, as in the default constructor, you're trying to initialize name , and age which both don't exist.

You probably meant newAge , and newName ?

In the other Constructor, name and age also don't exist, you probably meant n , and a ?

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