使用类通过main调用函数
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)
不存在,因为你没有在类定义之外定义它。
相关文章:
- 当我尝试在 Main 中调用插入函数时,它不是取数字?
- 未声明的标识符和类型"int"从 main 调用类时出现意外错误
- 如何使 WaitForSingleObject 在从 main 调用的线程内接收信号作为类成员函数
- C++尝试从main调用函数
- 如何用相同的签名从main调用基类函数
- C++ 如何从 main 调用派生的基类函数
- 读取函数由 main 调用,但不执行
- 如果方法私有,是否可以从 main 调用该方法?如果不是,怎么可能
- 使用类通过main调用函数
- 如果没有返回,如何向main调用void函数
- 在C++中从Main调用函数
- C++ 从实现文件中的 main 调用函数
- 从main调用c++源文件中的函数
- 如何在另一个包含对象的文件中创建一个函数并从 main 调用它
- 是否可以从常规main调用WinMain ?
- c++:从main()调用模板化函数
- 从c++中的main调用类中的结构体
- 在类中从main调用函数
- 未在作用域内声明的c++类——从main调用
- 如何编写函数并从main调用它们