簡體   English   中英

如何從c ++中的“指向對象的指針”向量訪問對象

[英]How do I access objects from a vector of “pointer-to-objects” in c++

我正在編寫一個程序來創建指向對象的指針。

如何從指針到對象向量訪問指針引用的各個對象?

我正在嘗試在類Object中為向量引用中的指針調用每個對象調用speak()函數。

感謝您的時間

class Object
{
public:
    void speak()
    {
        cout<<"Hello!"<<endl;
    }
};

int main()
{
    int choice;

    vector<Obj*> objVector; //create empty vector of "pointer-to-object"
    Object* ptrObj; //point to object

    while (choice!=5)
    {
        cout <<"1.Create Object\n";
        cout <<"2.Destroy Object\n";
        cout <<"3.Print number of existing Objects\n";
        cout <<"4.Tell existing Objects to say Hello\n";
        cout <<"5.Quit Program"<<endl;
        cout <<"Please enter your choice: ";
        cin >> choice;

    if (choice==5)
        cout <<"\nProgram is quitting\n"<<endl;
    else if (choice==1)
    {
        ptrObj= new Object;
        ObjVector.push_back(ptrObj); //adding an Object object
    }
    else if (choice==2)  //remove object
    {
        objVector.pop_back();
    }
    else if (choice==3)
    {
        cout <<"\nThere are " << objVector.size() <<" objects total.\n" << endl;
    }
    else if (choice==4)
    {
        for (int i=0; i<objVector.size(); i++)
        {
           ????????????
        }
    }
    }
    return 0;
}

最簡單的方法是使用*(objVector[i])

要訪問說話, objVector[i]->speak只是更短。

在現有代碼中,您可以完全按照在代碼中的其他位置使用它的方式訪問指針:

Object* obj = objVector[i];
obj->speak();
// or, simply:
objVector[i]->speak();

使用運算符->只是另一種說法(*objVector[i]).speak()

或者,編寫循環的慣用方法如下所示:

for(vector<Object*>::iterator it = objVector.begin(); it != objVector.end(); ++it) {
    // iterators work like another level of pointers, and need to be dereferenced:
    (*it)->speak();
}

如果您的編譯器支持C ++ 11,您可以像這樣重寫循環:

for(auto it = std::begin(objVector); it != std::end(objVector); ++it) {
    (*it)->speak();
}

或者像這樣,使用基於范圍的for,為你取消引用迭代器:

for(auto& obj : objVector) {
    obj->speak();
}

objVector[i] ,有些情況下你根本不確定objVector[i]是否在向量中,並且訪問它可能會使你的程序崩潰甚至導致惡魔從你的鼻腔飛出來。

為了增加安全性,您可以使用at函數引用向量中的位置,如下所示:

try {
    for (int i=0; i<objVector.size(); i++)
    {
        Object* obj = objVector.at(i);
        obj->speak();
    }
} catch (const std::out_of_range& ex) {
    cerr << "no object at position " << i << " in objVector" << endl;
    cerr << "objVector says " << ex.what() << endl;
}

但請注意,雖然它讓您有機會處理catch塊中的問題,但速度要慢很多。 如果at函數拋出異常, try塊將運行循環並停止並運行catch塊 - 這將是out_of_range類型的例外。 還要注意,使用[i]不會做同樣的事情,因為它不會拋出異常 - 它甚至都不會檢查i是否在向量的長度內。 這恰好也是[i].at(i)更快的原因。

最后,還要注意使用迭代器的循環不會遇到這個特定問題,只要在向量中添加或刪除某些東西后不嘗試使用迭代器。

你可以用*取消引用它們。 喜歡*(ObjVector [i])但是如果你只需要調用一個對象的方法就可以用 - > ObjVector[i]->speak()

與此問題無關,但我發表了一些評論來修改該計划。

正如其他人指出的那樣,你可以通過objVector[i]->speak()從vector中包含的指針調用對象函數。

然而,正如@greyfade指出的那樣,存在泄漏內存問題。 new創建對象時,您必須刪除對象。 您可以刪除對象通過delete這個樣子,

Object* ptr = objVector.back();
objVector.pop_back();
delete ptr;

要消除內存泄漏問題,可以將Object對象直接存儲在objVector而不是Object* 這樣,您不必擔心刪除對象。 你可以這樣做,

int main()
{
    int choice;

    vector<Object> objVector; //create empty vector of "pointer-to-object"

    while (choice!=5)
    {
        cout <<"1.Create Object\n";
        cout <<"2.Destroy Object\n";
        cout <<"3.Print number of existing Objects\n";
        cout <<"4.Tell existing Objects to say Hello\n";
        cout <<"5.Quit Program"<<endl;
        cout <<"Please enter your choice: ";
        cin >> choice;

    if (choice==5)
        cout <<"\nProgram is quitting\n"<<endl;
    else if (choice==1)
    {
        objVector.emplace_back(); //adding an Object object
    }
    else if (choice==2)  //remove object
    {
        objVector.pop_back();
    }
    else if (choice==3)
    {
        cout <<"\nThere are " << objVector.size() <<" objects total.\n" << endl;
    }
    else if (choice==4)
    {
        for (auto& obj : objVector)
        {
          obj.speak();
        }
    }
    }
    return 0;
}

此代碼使用c ++ 11功能。 您可以通過調用emplace_back來添加對象,並通過調用pop_back()刪除對象。 這不甜嗎?

還有一件事。 你忘記了標題上的一些代碼。 沒有這些頭文件,無法編譯此代碼,

#include <iostream>
#include <vector>
using namespace std;

如果此代碼可以幫助您,我會很高興。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM