未定义的类方法getValue()和运算符<<

时间:2015-11-27 17:06:22

标签: c++ class header-files

我有一个类Card在头文件card.h中实现并在card.cpp中定义,我试图创建两个非常简单的方法,一个是getValue(),当从源程序调用时main.cpp应该返回Card个私有成员之一。另一种方法是重载运算符<<我可以做,但显然不是在头文件中做同样的事情。这是代码

main.cpp中:

#include <fstream>
#include "header_files/card.h"
#include <vector>
using namespace std;

void print_vec(vector<Card>* a);

int main()
{
  ifstream file("poker.txt");
  vector<Card> cards;
  string read;

  while(file >> read) //READ THE FILE 
    cards.push_back(read);
  file.close();

  cards[0].getValue();
  return 0;
}

void print_vec(vector<Card>* a)
{
  for(int i = 0; i<a->size(); i++)
    cout << a->at(i) << "\n";
}

card.cpp:

#include "./../header_files/card.h"
Card::Card(std::string& s)
{
  whole_card = s;
  int size = s.size();
  if( s[0] >= 50 && s[0] <= 57 ) //check if its 2-9
    value = s[0] - 48; //convert to actual value from ASCII
  else if( s[0] == 84 ) //ASCII equivalent of T (i.e. 10)
    value = 10;
  else{ //must be ACE or J,Q,K
    switch( s[0] ){
    case 'A':
      value = 14; break;
    case 'J':
      value = 11; break;
    case 'Q':
      value = 12; break;
    case 'K':
      value = 13; break;
    }
  }

  //NOW SET THE SUIT FOR THE CARD
  suit = s[1];

}

std::ostream& operator<<(std::ostream& os, const Card& e)
{
  os << e.whole_card << "\n";
  return os;
}

char Card::getSuit()
{
  return suit;
}

int Card::getValue()
{
  return value;
}

card.h:

#ifndef CARD_H
#define CARD_H
#include <string>
#include <iostream>

class Card
{
  char suit;
  int value;
  std::string whole_card;
public:
  Card(std::string& s); //constructor prototype
  friend std::ostream& operator<<(std::ostream& os, const Card& e);
  char getSuit();
  int getValue();
};

#endif

然而,当我将所有代码编译在一起时,我收到以下错误:

main.o: In function `main':
main.cpp:(.text+0xca): undefined reference to `Card::getValue()'
main.o: In function `print_vec(std::vector<Card, std::allocator<Card> >*)':
main.cpp:(.text+0x18c): undefined reference to `operator<<(std::ostream&, Card const&)'

我已经仔细研究了一下,我不知道此时该做些什么。我刚开始尝试使用头文件和类,所以它有点乱。

谢谢

0 个答案:

没有答案