我不知道我能做些什么来使这个工作在C++中。C++对和指针
的打算是:
pair<int, int> foo() {
if(cond) {
return std::make_pair(1,2);
}
return NULL; //error: no viable conversion from 'long' to 'pair<int, int>
}
void boo() {
pair<int, int> p = foo();
if (p == NULL) { //error: comparison between NULL and non-pointer ('int, int' and NULL)
// doA
} else {
int a = p.first;
int b = p.second;
// doB
}
}
既然不能在C++中使用返回NULL,这里是我的第二次尝试:
pair<int, int>* foo() {
if(cond) {
return &std::make_pair(1,2); //error: returning address of local temporary object)
}
return nullptr;
}
void boo() {
pair<int, int>* p = foo();
if (p == nullptr) {
// doA
} else {
int a = p->first;
int b = p->second;
// doB
}
}
什么是正确的方法能够返回一个对和一个空值。
对于初学者来说,[避免对(http://maintainablecode.logdown.com/posts/158531 -stdpair考虑的有害)。 – Mark
使用'new'在堆上分配对。 – Barmar
@Barmar,不,只是没有。 – Shoe