[英]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.