我试图调用一个方法将对象添加到另一个对象中的向量。我收到了错误;
'': Illegal use of this type as an expression
在我的程序中,我声明一个对象将我的节点存储在main中;
accountStream *accountStore = new accountStream;
然后调用该函数;
new_account(&accountStore);
new_account函数为;
void new_account(accountStream &accountStorage)
{
newAccount *account = new newAccount;
(&accountStorage)->pushToStore(account);
}
帐户流类有一个接收它的向量,但我的错误就在哪里;
class accountStream
{
public:
accountStream();
~accountStream();
template <class account>
void pushToStore(account);
private:
std::vector <newAccount*> accountStore;
};
template<class account>
inline void accountStream::pushToStore(account)
{
accountStore.push_back(account);
}
错误发生在最后一行;
accountStore.push_back(account);
我感觉这与我将对象传递到方法中的方式有关,但在弄乱了一段时间之后,我还没有能够找出我出错的地方。
答案 0 :(得分:1)
2个问题:
new_account(&accountStore);
错误,请使用new_account(*accountStore);
来匹配参数类型。
accountStore.push_back(account);
错了。 account
类型不是对象。在函数中添加一些参数。
答案 1 :(得分:0)
几个问题:
您必须在此处指定变量名称(而不仅仅是类型):
template<class account>
inline void accountStream::pushToStore(account c)
{
accountStore.push_back(c);
}
您必须在此处收到指针(不是对指针的引用)
void new_account(accountStream *accountStorage)
{
newAccount *account = new newAccount;
accountStorage->pushToStore(account);
}
您必须使用指针作为参数调用该函数:
new_account(accountStore);
或者,您可以声明变量(不是指针):
accountStream accountStore;
调用函数:
new_account(accountStore);
并收到参考资料:
void new_account(accountStream &accountStorage)
{
newAccount *account = new newAccount;
accountStorage.pushToStore(account);
}
答案 2 :(得分:0)
正如这里已经回答的那样,你需要使用* accountStore而不是&amp; accountStore,因为该函数需要引用而不是指向指针的指针(这是你在指针上使用&amp;运算符得到的)。 p>
第二个问题在这里:
template<class account>
inline void accountStream::pushToStore(account)
{
accountStore.push_back(account);
}
您正在声明“帐户”上模板化的功能,因此帐户是一种类型,您在下一行中尝试执行的操作是push_back类型而不是对象。 正确的代码是:
template<class account>
inline void accountStream::pushToStore(account acct)
{
accountStore.push_back(acct);
}
因为帐户是类型,而acct是帐户类型的实例。