[英]undefined reference
我不熟悉在Linux下使用c ++的工作,所以遇到了一些問題,其中之一是在我編寫了一個類並嘗試實例化該類的對象后,出現以下錯誤:“未定義對Constructor_of_that_class的引用”。 這對於我編寫的每個類都會發生,並且無論我在哪里嘗試進行實例化都將發生這種情況,即使代碼可以毫無問題地進行編譯。 這里出了什么問題以及克服該錯誤我該怎么做? 因為我正在工作的項目不是我創建的,所以我懷疑它必須對某些設置進行某些操作,但我不知道該做什么。
編輯(從評論粘貼):
好吧,如果我定義一個類:
class test {
public:
int a*;
test( int* a)
}
class test {
test::test( int* a)
{
this->a=a;
}
}
然后在先前定義的那些人的任何類別中使用:
test t =new test( anIntPointer);
然后我得到未定義的引用test::test(int*)
;
如果您的代碼示例甚至可以編譯,我會感到驚訝,因此,首先修復所有其他編譯錯誤將是一個好的開始。 這是一個簡短的代碼示例,可能會有所幫助:
// Class declaration
class test
{
private:
// Member variable - should be private.
int* a;
public:
// Constructor declaration.
test(int* a);
// Inline function definition.
int getA()
{
return *a;
}
};
// Constructor declaration.
test::test( int* a)
{
this->a=a;
}
int main()
{
int i = 7;
test t(&i);
i++;
// Should return 8.
return t.getA();
}
沒有代碼,這是很難分辨的,但是要確保您的類定義以分號結尾;
做這個:
測試
class Test {
public:
int a*;
Test( int *a );
}; //Missing this semi colon might be your problem
測試文件
#include "test.h"
Test::Test( int *a )
{
this->a = a;
}
int main()
{
int *anIntPointer;
Test t = new Test( anIntPointer );
return 0;
}
不要將構造函數定義( test::test()
函數)包裝在class test
塊中。 這實際上定義了一個具有相同名稱的新類,但它與標頭中的類不同。 使它看起來像這樣:
// .h file
class test {
public:
int *a;
test( int* a)
};
// .cpp file
test::test( int* a)
{
this->a=a;
}
如果您想獲得更好的答案,則應提供您的某個類的代碼(定義+實現)。
通過您提供的最少說明,我認為您的構造函數沒有實現。
嘗試這個:
foo.h
class test {
public:
int a*;
test( int* a)
};
foo.cpp
test::test( int* a)
{
this->a=a;
}
除了我上面的評論(我的總血糖有些低)之外,語義還說明您正在實例化test
因此:
test t =new test( anIntPointer);
new
運算符返回指向對象的指針 ,而不是對象本身的指針 -您應該實例化它:
test *t = new test(anIntPointer);
(並且回到語義上,C ++類的約定是大寫的首字母,我相信:-))
您發布的課程定義在語法上無效。 正確的等效項是:
class test {
public:
int *a;
test (int *a) : a(a) {}
};
會編譯嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.