2017-04-17 85 views
-6

這樣做的正確語法是什麼?當然,我犯了一個愚蠢的錯誤...不幸的是,我試圖更好地理解載體。我知道我創建了一個不必要的指針,但我需要理解語法。將對象向量返回給函數

#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*)' 
+0

'getVector'聽起來像它應該返回一個向量,而不是'otherClass'。 – aschepler

+0

它不清楚你想要做什麼。你想從一個函數返回一個向量? – pm100

+0

這個程序可以簡化爲'std :: cout << 5 << std :: endl;' – myaut

回答

1

首先,有在這裏使用任何指針是沒有意義的。沒有!

其次,您的獲得者應該被限定爲const,並返回像矢量這樣的重物的const引用。它可以防止無用的副本。

int getValue() const 
//    ^^^^^ 
{ 
    return value; 
} 

otherClass

class MyClass 
{ 
public: 
    MyClass(int x) : obj(x, otherClass{5}) // construction here 
    { } 
    std::vector<otherClass> const & getVector() const 
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^    ^^^^^ 
    { 
     return obj; 
    } 
private: 
    std::vector<otherClass> obj; // no pointer, just a vector 
}; 

然後在主:

MyClass aClass(10); 

你想與doSomething()做什麼還不清楚。用您的代碼doSomething(aClass->getVector())您應該處理otherClass es的返回矢量。所以它應該是:

void doSomething(std::vector<otherClass> const & obj) 

我讓你寫它的代碼。

+0

但是在我的程序中,「obj」是一個指針,因爲那時我需要用「delete」來銷燬它。 「aClass」是一個指針,出於同樣的原因... – nostyn

+1

@nostyn它不應該。這沒有理由。 –

+0

所以,如果我想用指針做到這一點,我可以不?爲什麼?我不能將obj地址傳遞給函數,並避免不必要地分配更多內存? – nostyn

0

只是說要返回

std::vector<otherClass> *getVector() 
{ 
    return obj; 
} 
什麼

std::vector<otherClass> getVector() 
{ 
    return *obj; 
} 
+1

另外,不要在第二種情況下返回一個const引用。 –

+0

我只是想讓OP移動一下,顯然有很多很多東西錯誤提供的代碼 – pm100

+0

有點在錯誤的方向... –