[英]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.