簡體   English   中英

如何在類構造函數中初始化數組?

[英]How to initialize an array in a class constructor?

使用C ++在Mac OS X Leopard上使用Xcode

我有以下代碼:

class Foo{

private:
    string bars[];

public:
    Foo(string initial_bars[]){
        bars = initial_bars;
    }
}

它不編譯並拋出以下錯誤:

error: incompatible types in assignment of 'std::string*' to 'std::string [0u]'

我注意到刪除了line bars = initial_bars; 解決了這個問題。 好像我沒有正確地完成任務。 我怎么能解決這個問題呢?

編輯:

變量條是一個字符串數組。 在main函數中,我將它初始化為:

string bars[] = {"bar1", "bar2", "bar3"};

但它可以包含任意數量的成員。

數組的行為類似於const指針,您無法為它們指定指針。 您也無法直接為彼此分配數組。

你要么

  • 使用指針成員變量
  • 你得到一個固定大小的bar並用你的內容初始化你的成員數組
  • 只需使用std容器的引用,如std::vector

可以按如下方式“值初始化”數組成員:

class A {
public:
  A () 
  : m_array ()       // Initializes all members to '0' in this case
  {
  }

private:
  int m_array[10];
};

對於POD類型,這很重要,就好像您沒有在成員初始化列表中列出'm_array'那樣數組元素將具有不確定的值。

通常,最好在member-initialization-list中初始化成員,否則成員將初始化兩次:

A (std::vector<int> const & v)
// : m_v ()   // 'm_v' is implicitly initialized here
{
  m_v = v;    // 'm_v' now assigned to again
}

更有效地寫作:

A (std::vector<int> const & v)
: m_v (v)
{
}

暫無
暫無

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

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