這是assign_obj我想要列印物件的類、建構式和運算子的一部分。嘗試編譯運算子時出現錯誤:
error: 'A' was not declared in this scope for(assign_obj::item anItem : obj.*A){
這是為什么?如果我obj.A改為嘗試,我會得到 forloop 錯誤,因為 C 無法回圈動態陣列的指標。
class assign_obj{
private:
struct item{
char value;
int count;
};
item * A; //pointer A pointing to something of type Item
int size;
public:
assign_obj();
assign_obj(std::string);
friend std::ostream& operator<<(std::ostream & out, assign_obj & obj);
//Constructor
assign_obj::assign_obj(string aString){
size = aString.size();
A = new item[size];
item myItem;
for(int i = 0; i < size; i ){
myItem = {(char)toupper(aString[i]), 1};
A[i] = myItem;
}
}
// Print operator
std::ostream& operator<<(std::ostream & out, assign_obj & obj){
out <<"[ ";
for(assign_obj::item anItem : obj.*A){
out << anItem.value;
out << ":";
out << anItem.count;
out << " ";
}
out <<"]";
return out;
}
uj5u.com熱心網友回復:
對于動態分配的陣列,您不能以這種方式使用 for 回圈。您可以為普通的舊陣列使用普通的舊 for 回圈。
std::ostream& operator<<(std::ostream & out, assign_obj & obj){
out <<"[ ";
for (size_t i = 0; i < obj.size; i ) {
out << obj.A[i].value << ":"
<< obj.A[i].count << " ";
}
out <<"]";
return out;
}
uj5u.com熱心網友回復:
在 c 中,通常建議使用std::vector,而不是原始 c 陣列。
您需要添加:
#include <vector>
那么您的會員將是:
std::vector<item> A;
分配專案assign_obj::assign_obj是這樣完成的:
A.resize(size);
最后你operator<<將是:
std::ostream& operator<<(std::ostream & out, assign_obj & obj){
out <<"[ ";
//-----------------------vvvvvvv----------vvvvv--
for(assign_obj::item const & anItem : obj.A){
out << anItem.value;
out << ":";
out << anItem.count;
out << " ";
}
out <<"]";
return out;
}
筆記:
- 訪問
A成員obj是用 完成的obj.A,而不是obj.*A。 - 使用 a 完成對向量的遍歷
const&以避免復制。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/530130.html
標籤:C 指针
下一篇:使用指標以相反的順序列印陣列元素
