[英]Calling a function via the main using a class
我正在尝试使用函数将 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)
不存在,因为您没有在类定义之外定义它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.