2016-04-23 67 views
3

我無法訪問字符串數組。它被聲明爲一個私有數組並填充到該類的構造函數中。我有一個Get函數定義。問題是當我在編譯時調用這個函數時,我得到一個錯誤,我無法訪問在類中聲明的私有成員。我只是回到編碼中,爲了這個yuks,因此我處於一個階段的前期指針和預向量階段,所以我試圖避免會迫使他們使用的情況。無法訪問專用陣列

Words.h

#pragma once 
#include <string> 
#include <iostream> 
#include <array> 

class Words { 
    Words(); 

    public: 
     std::string GetNewWord(int); 

    private: 
     std::string WordList[23] = {}; 
}; 

Words.cpp - 數組完全填滿,但這裏縮短

#include "Words.h" 

Words::Words(){ 
    WordList[0] = "omega"; 
    WordList[1] = "minors"; 
    WordList[2] = "stigma"; 
    WordList[3] = "glamor"; 
    WordList[4] = "savior"; 
    WordList[5] = "disarm"; 
    WordList[6] = "isogram"; 
    . 
    . 
    . 
    ; 
} 

std::string Words::GetNewWord(int choice) 
    { 
     return WordList[choice]; 
    } 

的main.cpp - 包含一個無限循環,所以我可以快速測試如果陣列填充

#include <iostream> 
#include <string> 
#include "Words.h" 

Words word; 

int main() { 

    do { 
     std::cout << "choice: "; 
     int choice; 
     std::cin >> choice; 
     std::cout << "\n" << word.GetNewWord(choice) << "\n"; 

    } while (true); 

    return 0; 
} 

回答

3

構造函數是私有的,作爲一類的所有成員都是由defau LT。只需將其移動到公共部分即可。

+0

有一個私人詮釋或其他類型與數組之間有什麼區別。大多數文本都表示,任何屬於該類的靜態變量或數據都會默認標記爲私有標記,或者使用私有標記進行標記,然後定義get/set方法以訪問它們。你的建議可以解決這個問題,但是會產生一個新的問題:什麼是使用類定義數組的正確方法與其他類定義的數據。 – Wes

+0

完全沒有區別。你的問題與成員數組或getter方法無關。你的類的構造函數是私有的,因此無法訪問。這就是編譯器的抱怨。 –