简体   繁体   English

C ++参考和指针

[英]C++ References and Pointers

I have the following code in my program for a blackjack game: 我的二十一点游戏程序中有以下代码:

Player *p;
Deck *d = new Deck();
Hand *playerHand = new Hand(), *dealerHand = new Hand();
p = get_Simple();  //This returns a pointer to an instance of a Simple Player for my game
Card dealerCard = d->deal();
p->draw(dealerCard, playerHand);

draw is defined as 平局定义为

virtual bool draw(Card dealer, const Hand &player);

When I try to run this code, I get the following error: 当我尝试运行此代码时,出现以下错误:

error: no matching function for call to 'Player::draw(Card&, Hand*&);
note: candidates are: virtual bool Player::draw(Card, const Hand&);

The quick-fix would be to match the call with the signature: 快速解决方案是将呼叫与签名匹配:

p->draw(dealerCard, *playerHand);

The correct way would be to go about your code and get rid of dynamic allocation and raw pointers, replacing them with smart pointers. 正确的方法是处理您的代码并摆脱动态分配和原始指针,而将其替换为智能指针。

The error message is quite clear (after seeing it a couple of times): 该错误消息非常清晰(几次见后):

error: no matching function for call to 'Player::draw(Card&, Hand*&); 错误:没有匹配的函数调用'Player :: draw(Card&,Hand *&); note: candidates are: virtual bool Player::draw(Card, const Hand&); 注意:候选人为:虚拟bool Player :: draw(Card,const Hand&);

In the code you are trying to pass a Card and a Hand* to a function, but the compiler did not find an overload that takes those. 在代码中,您尝试将CardHand*传递给函数,但是编译器未找到需要这些函数的重载。 The closest it got is a function that takes a Card and a const Hand& . 它得到的最接近的函数是Cardconst Hand&

You need to dereference the pointer to get to the object: 您需要取消引用指针才能到达对象:

p->draw(dealerCard, *playerHand);

Alternatively consider whether you need to hold all objects by pointer or not. 或者,考虑是否需要通过指针保存所有对象。 Code is much simpler if you avoid pointers. 如果避免使用指针,则代码要简单得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM