[英]Returning specific values of a struct
是否可以(盡管可能不是很好的做法)立即從函數設置結構的值? 例如 :
typedef struct
{
bool success;
std::string returnString;
} functionReturn;
functionReturn go(std::string word[])
{
functionReturn returnStruct;
...
return returnStruct;
}
int main()
{
std::string word[4];
... //assign values to word
std::string returnedString = go(word).returnString //will this work?
}
這可能嗎,或者實際上我是否必須將其分配給另一個函數返回並從中提取字符串值?
是的,這完全有可能; 與調用返回對象的成員函數沒有什么不同,這很正常:
std::ostringstream s;
s << "file" << i;
std::ifstream f(s.str().c_str()); //notice calls here
請不要使用typedef struct {...} name;
C ++中的成語。 這是C的保留,在C ++中沒有任何價值。 只需使用標准技術即可: struct name {...};
從技術上講 ,做自己的事情沒有錯。 請注意,不要返回對本地或類似內容的引用。 你不在這里
實際上,您可能有一個對參數執行某些操作並返回對該對象的引用的方法,然后將方法調用鏈接在一起,如下所示:
struct functionReturn
{
functionReturn& doSomething() { return * this; }
functionReturn& doSomethingElse() { return * this; }
};
int main()
{
functionReturn fr;
fr.doSomething().doSomethingElse();
}
這也是有效的。 這稱為方法鏈接 。 問題不是天氣是否有效,而是語義是否清晰且可維護。 有些人認為這樣的結構優雅簡潔。 其他人則認為這是可憎的。 在后一組算我。 自行決定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.