我正在尝试学习 C++ 并弄清楚如何访问作为对象数组的私有(private)成员变量。我的目标是尝试打印出对象数组中的数据。假设我的标题如下所示。
using namespace std;
const unsigned MAX_RESULTS = 10;
class StudentRecords{
public:
StudentRecords();
//bunch of other getters and setters here
Result GetResults() const; //my lame attempt at trying to access the obj-array private var
private:
Result results[MAX_RESULTS]; // array of Result of MAX_RESULTS number of elements
//+other private variables
};
ostream& operator <<( ostream& os, const StudentRecords& R);
在上面,应该有一个名为 results 的私有(private) Result 对象数组,它的大小为 MAX_RESULTS,这里应该是 10。现在,使用我的重载运算符 << 可以说,其想法是将 Result 的内容打印到"file"。由于它是一个数组,所以我想使用 for 循环打印出数组中的所有结果。
Result StudentRecords::GetResults() const
{
return results[MAX_RESULTS];
}
ostream & operator <<( ostream & os, const StudentRecords& R )
{
for(unsigned i = 0; i < SomeNumber; i++)
{
os << R.GetResults()[i] << '\n'; //this won't work of course see error
}
return os;
}
将会出现错误:
error: no match for 'operator[]' (operand types are 'Result' and 'unsigned int')|
我已经在 Result 类中重载了 << 运算符,以便打印出该类中的值。问题是我不知道如何迭代结果数组。根据我在谷歌上搜索的内容,我了解到您可以使用某种指针函数,例如:C++: Setters and Getters for Arrays
当我尝试编写这样的函数时:
Result* GetResults() const;
我会收到一条错误消息:
error: cannot convert 'const Result' to 'Result*' in return|
省略 * 可以让代码编译,但可以预见的是,我从数组中得到了一堆垃圾值。因此,假设我的类有一个对象数组,并且这些对象有自己的变量,我如何从对象数组中打印出值?我很感谢您的帮助。
最佳答案
Result StudentRecords::GetResults() const
{
return results[MAX_RESULTS];
}
这是新手常见的误解。因为您将数组声明为results[MAX_RESULTS]
,您认为results[MAX_RESULTS]
在某种程度上意味着整个数组。但事实并非如此,当您使用数组时,[]
用于访问数组的各个元素。当然,索引 MAX_RESULTS
处没有元素,它超出了数组的末尾。
底线是声明的语法和表达式的语法不同。
你可以做这样的事情
const Result* StudentRecords::GetResults() const
{
return results;
}
这会返回一个指向数组的指针,而不是数组本身(这在 C++ 中实际上是不可能做到的)。但现在应该已经足够接近了。
关于c++ - 在 C++ 中,如何使用作为对象数组的私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72540603/