#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
using namespace std;
class car{
private:
string color;
int mileage;
int topSpeed;
int numGears;
public:
};
class carNode{
private:
car Car;
carNode *next;
friend class carLinkedlist;
};
class carLinkedlist{
public:
carLinkedlist();
~carLinkedlist();
bool empty() const;
void addtolist(const car& theCar);
const carNode* getHead();
private:
carNode* head;
};
const carNode* carLinkedlist::getHead(){
return head;
}
void car::setDetails(const string color,const int mileage,const int topSpeed,const int numGears){
this->color = color;
this->mileage = mileage;
this->topSpeed = topSpeed;
this->numGears = numGears;
}
carLinkedlist::carLinkedlist(){
head = NULL;
}
carLinkedlist::~carLinkedlist(){
// what to do here
}
bool carLinkedlist::empty() const{
if (head==NULL)
return true;
return false;
}
void carLinkedlist::addtolist(const car& theCar){
if (empty()){
head = new carNode;
head->Car = theCar;
head->next = NULL;
}
else{
carNode* temp = new carNode;
temp->Car = theCar;
temp->next = NULL;
head->next = temp;
}
}
int main(){
car car1;
car1.setDetails("red",40,140,5);
const car& carr1 = car1;
car car2;
car2.setDetails("black",30,220,5);
const car& carr2 = car2;
carLinkedlist carList;
carList.addtolist(carr1);
carList.addtolist(carr2);
//cout << car1.getColor() << endl;
cout << (carList.getHead())->next->Car.getColor() << endl;
return 0;
}
此代码在第二行最后一行抛出错误,而且Car都是私有的。我可以创建一个getCar函数来访问Car的值,但是对于受保护的next,该怎么做,我该如何访问它的值。
P.S。我出于类似的原因制作了getHead函数,即访问头部但我无法通过函数访问下一个函数,因为接下来将会有下一个&gt;受保护。 另外请验证我是否应该制作getCar函数或执行其他操作。
答案 0 :(得分:0)
一种解决方案是成为next
成员public
。
另一种解决方案是在link_to
内添加carNode
函数:
class carNode
{
public:
void link_to(carNode& cn)
{
next = &cn;
}
private:
//...
};