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;
}
有一个私人诠释或其他类型与数组之间有什么区别。大多数文本都表示,任何属于该类的静态变量或数据都会默认标记为私有标记,或者使用私有标记进行标记,然后定义get/set方法以访问它们。你的建议可以解决这个问题,但是会产生一个新的问题:什么是使用类定义数组的正确方法与其他类定义的数据。 – Wes
完全没有区别。你的问题与成员数组或getter方法无关。你的类的构造函数是私有的,因此无法访问。这就是编译器的抱怨。 –