使用类通过main调用函数

Calling a function via the main using a class

本文关键字:main 调用 函数      更新时间:2023-10-16

我试图使用函数将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;
}

定义的成员函数int Test::addTwo(int test)与编译器搜索的声明的全局函数int addTwo(int test);不同。

若要消除错误,请定义全局函数或将全局函数的调用更改为成员函数的调用。

为了"使用函数将2添加到类变量",您应该停止通过参数隐藏成员变量。(您可以使用this->test来使用成员变量,但在这种情况下不需要这样做)

试试这个:

#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;
}

由于它是实例test的成员函数,因此必须将其称为

test.addTwo(test.test);

相反,你称之为

addTwo(test.test);

它不知道这个函数是什么。就编译器而言,addTest(int)不存在,因为你没有在类定义之外定义它。