2017-10-06 209 views
-3

我有一個頭文件,其中定義了一個類,並且還使用unique_ptr訪問類成員。
但我不知道如何從clone.cpp 一般訪問它,我們要做的就是創建一個類 的對象例如:如何使用unique_ptr訪問C++中的類成員和類變量

A obj; 
bool res = obj.concate("hello"); 

我們如何能做到這一點使用的unique_ptr?

當我試圖做

bool result = access->concate("hello"); 

我收到以下錯誤:

Undefined symbols for architecture x86_64: 
"obja()", referenced from: 
    _main in classA.o 
ld: symbol(s) not found for architecture x86_64 
clone.h 
-------- 

std::unique_ptr<class A> obja(); 

class A 
{ 
public: 
    bool concate(string str){ 
    string a = "hello"; 
    return a == str; 
    } 
private: 
    string b = "world"; 
}; 


clone.cpp 
________ 

int main(){ 
auto access = obja(); 
return 0; 
} 
+1

與解引用原始指針一樣,使用' - >'運算符。 – user0042

+0

哦,男孩:https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-doi-i-fix – user0042

+0

錯誤似乎很清楚。你已經聲明瞭一個名爲'obja'的函數,並且你正在調用它 - 但是你還沒有實現它。 –

回答

0

你不需要std::unique_ptr<class A> obja();,同約方括號。

不知道什麼R您想在這裏實現:auto access = obja(); 我想你想那裏調用concate,那麼一切都可以是這樣的:

class A 
{ 
public: 
    bool concate(string str) { 
     string a = "hello"; 
     return a == str; 
    } 
private: 
    string b = "world"; 
}; 

std::unique_ptr<A> obja; 

int main() { 
    auto access = obja->concate("test"); 
    return 0; 
} 
0
class A 
{ 
     public: 
     bool concate(string str) { string a = "hello"; return a == str; } 

     private: string b = "world"; 
}; 

std::unique_ptr<A> obja = std::make_unique <A>; 

int main() { 
    auto access = obja->concate("test"); return 0; 
} 

你只是忘記分配內存。 :)