无法访问私有阵列

Unable to access a Private Array

我无法访问字符串数组。它被声明为私有数组并填充在 class 的构造函数中。我定义了一个 Get 函数。问题是当我在编译时调用此函数时出现错误,提示我无法访问 class 中声明的私有成员。我只是重新开始为 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;
}

构造函数是私有的,因为默认情况下 class 的所有成员都是私有的。只需将其移动到 public 部分。