2013-10-02 32 views
0

我知道它可能看起來像這樣以前已經問過,但我環顧四周,static方法不適用於我。這裏是我的代碼:不能調用成員函數std :: string class :: function()without object

struct Customer { 
public: 
    string get_name(); 
private: 
    string customer,first, last; 
}; 

這裏就是我所說的功能:

void creation::new_account() { 
Customer::get_name(); //line it gives the error on. 
} 

下面是一些代碼,編譯罰款的例子。

struct Creation { public: string get_date(); private: string date; }; 

然後我把它以同樣的方式

void Creation::new_account() { Creation::get_date();} 

因此我的困惑,爲什麼一個工程和其他沒有。

編輯:好的我明白了,我只是意識到我正在調用一個函數定義中的另一個結構的函數,這是另一個類的一部分。我明白了,謝謝所有回答

+0

它**不** *靜態*,你應該把它通過一個對象。 – Maroun

+0

正如所指出的那樣,你錯過了將函數聲明爲靜態的,因此錯誤。你可以把原來的代碼放在「靜態」不適合你的地方嗎? – NotAgain

+0

@NotAgain肯定是這個'struct客戶{ public: static string get_name(); 私有: 串客戶,第一,最後; };' – Shilaly

回答

1

未聲明static(需要爲static std::string get_name();)。但是,get_name()對於CustomerCustomer實例的特定屬性,因此使其具有static沒有意義,這對於Customer的所有實例而言都是相同的名稱。聲明Customer的對象並使用它。它將使意義有提供給Customer構造函數的名稱,這是肯定的顧客不能沒有名字的存在:

class Customer { 
public: 
    Customer(std::string a_first_name, 
      std::string a_last_name) : first_name_(std::move(a_first_name)), 
             last_name_(std::move(a_last_name)) {} 
    std::string get_name(); 
private: 
    std::string first_name_; 
    std::string last_name_; 
}; 

聲明的Customer一個實例:

Customer c("stack", "overflow"); 
std::cout << c.get_name() << "\n"; 
+0

謝謝,我試圖避免傳遞一個對象,但我想一個空對象將爲我的目的工作。 – Shilaly

0

由於您的get_name沒有被聲明爲靜態,所以它是一個成員函數。

您可能需要在您的Customer類中使用一些構造函數。假設你有一些,你可以編寫

Customer cust1("foo123","John","Doe"); 
string name1 = cust1.get_name(); 

你需要一個對象(這裏cust1)來調用它get_name成員函數(或方法)。

花費很多時間閱讀一本好的C++編程書的時間。

0

「的static方法沒不爲我工作「。這不是一種語言如何工作的方法。

如果你想調用一些沒有具體對象的方法,你需要它是靜態的。否則,你需要一個對象。

你的代碼將與下面的一個工作:

struct Customer { 
public: 
    static string get_name(); 
private: 
    string customer,first, last; 
}; 

void creation::new_account() { 
    Customer c; 
    //stuff 
    c.get_name(); 
} 
+0

對不起,我鍵入的方法,但語義拋開,我的意思是我鍵入靜態字符串get_name();編譯器抱怨。 但謝謝第二個工作。我困惑的原因是因爲我有兩個其他函數定義和聲明相同,我創建了另一個只是爲了確保沒有這個函數編譯好。 – Shilaly

+0

@Shilaly如果編譯器在實際使用'static string get_name();'的時候抱怨,那麼你在其他地方發生了另一個錯誤...... – JBL

相關問題