2016-05-05 84 views
-1

我試圖用函數將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; 
} 
+1

聲明的東西沒有定義它。 – MikeCAT

回答

1

定義的成員函數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; 
} 
+0

推薦對第一句話進行編輯,粗暴地指出'addTwo(test.test);'與'int addTwo(int test);'而不是'int Test :: addTwo(int test);'**匹配**'addTwo(test.test);'不在對象上調用。 – user4581301

0

既然是實例test的成員函數,你必須把它作爲

test.addTwo(test.test);

相反,你叫它爲

addTwo(test.test);

它並不知道那個函數是什麼。就編譯器而言,addTest(int)不存在,因爲您尚未將其定義在類定義之外。