2016-05-05 42 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)不存在,因为您尚未将其定义在类定义之外。