简体   繁体   中英

Calling a function via the main using a class

I'm trying to add 2 to a class variable using a function, but it gives me this undefined reference to addTwo(int) even though I already have it declared.

#include <stdio.h>
#include <iostream>

using namespace std;

class Test {

    public:
        int addTwo(int test);
        int test = 1;
};    

int addTwo(int test);

int main() {

    Test test;

    cout << test.test << "\n";

    addTwo(test.test);

    cout << test.test;
}

int Test::addTwo(int test) {
    test = test + 2;
    return test;
}

The defined member function int Test::addTwo(int test) do differ from the declared global function int addTwo(int test); , which the compiler searches for.

To eliminate the error, define the global function or change the call of the global function to call of the member function.

In order to "add 2 to a class variable using a function", you should stop shadowing the member variable by the argument. (You can use this->test for using member variable, but this won't be needed in this case)

Try this:

#include <iostream>
using namespace std;

class Test {

    public:
        int addTwo();
        int test = 1;
};    

int main() {

    Test test;

    cout << test.test << "\n";

    test.addTwo();

    cout << test.test;
}

int Test::addTwo() {
    test = test + 2;
    return test;
}

Since it is a member function of the instance test you have to call it as

test.addTwo(test.test);

Instead, you're calling it as

addTwo(test.test);

and it doesn't know what that function is. As far as the compiler is concerned, addTest(int) doesn't exist because you haven't defined it outside of the class definition.

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