简体   繁体   English

使用类通过 main 调用函数

[英]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.我正在尝试使用函数将 2 添加到类变量,但它给了我这个undefined reference to addTwo(int)即使我已经声明了它。

#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);定义的成员函数int Test::addTwo(int test)确实不同于声明的全局函数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.为了“使用函数将 2 添加到类变量”,您应该停止通过参数隐藏成员变量。 (You can use this->test for using member variable, but this won't be needed in this case) (您可以使用this->test来使用成员变量,但在这种情况下不需要这样做)

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的成员函数,因此您必须将其称为

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.就编译器而言, addTest(int)不存在,因为您没有在类定义之外定义它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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