簡體   English   中英

如何為 c++ 中對象指針的常量向量賦值?

[英]How to assign value to const vector of pointers of objects in c++?

我目前正在嘗試將值分配給 const std::vector。 年齡是 class 源自 class 動物。

#include <iostream>
#include <vector>

class Animal{
  public:
    Animal(std::string name) : name_(name) {}
    std::string getName() {return name_;}
  protected:
    std::string name_;
};


class Age : public Animal
{
  public:
    Age(std::string name, int age) : Animal(name), age_(age) {}
  private:
    int age_;
};

class AllAnimals
{
  public:
    AllAnimals(){};
    void setVector(const std::vector<Age*> v) {all_animals_ = v;}
  private:
    const std::vector<Age*> all_animals_;
};



int main()
{
  AllAnimals animals();
  std::vector<Age*> all_animals;
  all_animals.push_back(new Age("Cat", 3));
  all_animals.push_back(new Age("Dog", 4));
  all_animals.push_back(new Age("Mouse", 2));
  all_animals.push_back(new Age("Duck", 1));
  return 0;
}

編譯代碼后,我收到錯誤消息:

 error: passing ‘const std::vector<Age*>’ as ‘this’ argument discards qualifiers [-fpermissive] void setVector(const std::vector<Age*> v) {all_animals_ = v;}

我的實現有什么問題,如何為 all_animals_ 分配值?

初始化后不能分配給向量,它是const 解決方案是初始化它。 由於您的代碼正在處理原始擁有的指針,並且需要一些關於正確使用它們或使用智能指針的提醒,但這不是問題的主題,我讓自己簡單地舉了很多例子:

#include <vector>

struct foo {
    const std::vector<int> x;
    foo(const std::vector<int>& a) : x(a) {}
};

int main() {
    std::vector<int> v{1,2,3,4};
    foo f(v);
}

成員在構造函數的主體執行之前被初始化,因此初始化它的地方是構造函數成員初始化列表。

請注意,使成員const很少是一個好主意。 例如,當實例具有const成員時,您不能復制它們。 如果您希望成員在構造后不被修改,這是封裝真正得到回報的情況。 將成員設為私有,並且不提供來自外部的任何寫訪問權限。 然后從外部成員是不可修改的,但您仍然可以復制 class 的實例。

PS:這里的錯誤信息可能有點混亂。 它指的是std::vector= ,因此消息中的this是向量,而不是您的AllAnimals實例。 當成員 function 存在 const 正確性問題時,“將 XY 作為 'this' 參數傳遞會丟棄限定符”是典型的錯誤消息。

暫無
暫無

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

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