這樣做的正確語法是什麼?當然,我犯了一個愚蠢的錯誤...不幸的是,我試圖更好地理解載體。我知道我創建了一個不必要的指針,但我需要理解語法。將對象向量返回給函數
#include <iostream>
#include <vector>
class otherClass
{
public:
otherClass(int x):value(x)
{
//ctor
}
int getValue()
{
return value;
}
private:
int value;
};
class MyClass
{
public:
MyClass(int x)
{
obj = new std::vector<otherClass>(x,otherClass{5});
}
otherClass getVector()
{
return obj; //HERE FIRST ERROR <---------------
}
private:
std::vector<otherClass>*obj;
};
void doSomething(otherClass*obj)
{
std::cout << obj->getValue() << std::endl;
}
int main()
{
MyClass*aClass = new MyClass(10);
doSomething(aClass->getVector()); //HERE SECOND ERROR <---------------
return 0;
}
錯誤編譯時,我得到:
第一:
error: invalid conversion from 'std::vector<otherClass>*' to 'int' [-fpermissive]
二:
error: cannot convert 'otherClass' to 'otherClass*' for argument '1' to 'void doSomething(otherClass*)'
'getVector'聽起來像它應該返回一個向量,而不是'otherClass'。 – aschepler
它不清楚你想要做什麼。你想從一個函數返回一個向量? – pm100
這個程序可以簡化爲'std :: cout << 5 << std :: endl;' – myaut