我想解决这个指针/类的问题,我坚持创建一个函数调用add(string t)
。编写add(string t)函数的最佳方法是什么?我不能在main()内部修改。这只是一个愚蠢的代码,你移动你的火车。这里是一个输出的例子:指针/类C++
Current train: Engine
Do you wish to go to the (n)ext train, (p)revious train, (a)dd a train, or (q)uit?
a
Which train is this?
4
Current train: Engine
Previous train: 4
Do you wish to go to the (n)ext train, (p)revious train, (a)dd a train, or (q)uit?
a
Which train is this?
1
Current train: Engine
Previous train: 1
Do you wish to go to the (n)ext train, (p)revious train, (a)dd a train, or (q)uit?
p
任何提示是非常感谢。谢谢!节日快乐。
#include <iostream>
using namespace std;
class train
{
private:
string s;
train* next_train;
train* previous_train;
train* has_next;
train* has_previous;
public:
train(string name);
string getName();
train* nextTrain();
train* previousTrain();
train* hasNext();
train* hasPrevious();
void add(train *t);
};
int main()
{
train engine = train("Engine");
train* current = &engine;
string choice;
do
{
if(current -> hasNext())
{
cout << "Next train: " << current -> nextTrain() -> getName() <<
endl;
}
cout << "Current train: " << current -> getName() << endl;
if(current -> hasPrevious())
{
cout << "Previous train: " << current -> previousTrain() -> getName()
<< endl;
}
cout << "Do you wish to go to the (n)ext train, (p)revious train,
(a)dd a train, or (q)uit?\n";
getline(cin,choice);
if(tolower(choice[0]) == 'n' && current -> hasNext())
{
current = current -> nextTrain();
}
else if(tolower(choice[0]) == 'p' && current -> hasPrevious())
{
current = current -> previousTrain();
}
else if(tolower(choice[0]) == 'a')
{
cout << "Which train is this?\n";
string name;
getline(cin, name);
current->add(name);
}
}while(tolower(choice[0]) != 'q');
}
train::train(string name)
{
s = name;
}
string train::getName()
{
return s;
}
train* train::nextTrain()
{
return next_train;
}
train* train::previousTrain()
{
return previous_train;
}
train* train::hasNext()
{
return has_next;
}
train* train::hasPrevious()
{
return has_previous;
}
void train::add(string *t)
{
train* current;
current = &t;
}
什么是你的问题?你只希望有人为你写这个功能? –
我不喜欢'has_next'或'has_previous'。你要去哪里? – user4581301
@CareyGregory如果我只是想让别人为我写这个函数,那你很高兴问我这个问题。如果是这样,我可以支付某人这样做,而不是在这里。你明白吗?有时,我认为当人们发布问题时,并不一定是问题类型。在这种情况下,如果你认为我需要发布一个问题,那么这将是:在我的代码中使用add函数的最佳方式是什么?不是“你能为我写入添加功能吗?”谢谢! – Hugh