TommyL
TommyL

Reputation: 33

Why are my functions undefined when I declared the type already?

Hi I was just trying to learn separate Classes in C++. I don't know why my code is not working. So here is the main file code

#include <iostream>
#include "Number.h"

using namespace std;

int main()
{
    Number key;
    key.setNumber(200);
    cout<<key.getNumber();
    return 0;
}

Here is the Class cpp functions file code

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

void Number::setNumber(int transfernumber)
    {
    privatenumber = transfernumber;
    }

int Number::getNumber()
    {
        return privatenumber;
    }

And here is the header file

#ifndef NUMBER_H
#define NUMBER_H


class Number
{
    public:
        Number();
        void setNumber(int transfernumber);
        int getNumber();
    private:
        int privatenumber;
};

#endif // NUMBER_H

Thanks

Upvotes: 2

Views: 47

Answers (2)

cwfighter
cwfighter

Reputation: 502

I have test your example. The error happened for the main.cpp cannot found the number.cpp. You have three ways to solve it:

  1. write your main() to the number.cpp, not a solo file.
  2. complie the main.cpp with the linux command gcc or write a Makefile, instead of using codeblocks.
  3. If you want to use the codeblocks for compiling, you should create a project, and then add your three files to the project. Now compile the main.cpp.

Use the three ways above, I think you will compile successfully.

BTW, you should add the Number::Number() 's implementation.

Upvotes: 0

Phil
Phil

Reputation: 6174

In your cpp file you need to define the default constructor for the Number class. For example:

Number::Number() : privatenumber(0) {}

Upvotes: 2

Related Questions