c++ - 使用#pragma once 和#ifndef 时 VS 2010 C++ LNK2005 错误

标签 c++ lnk2005

1>Deck.obj : error LNK2005: "class Card card" (?card@@3VCard@@A) already defined in Card.obj
1>PokerTester.obj : error LNK2005: "class Card card" (?card@@3VCard@@A) already defined in Card.obj
1>PokerTester.obj : error LNK2005: "class Deck deck" (?deck@@3VDeck@@A) already defined in Deck.obj
1>C:\Dev\Poker\Debug\Poker.exe : fatal error LNK1169: one or more multiply defined symbols found

我已经通过谷歌搜索了解了为什么会出现这些错误,但我不知道为什么当我尝试了#pragma once 和#ifndef 保护时它们仍然发生。

这是我的卡片.h

#pragma once

#ifndef CARD_H
#define CARD_H

#include <iostream>
#include <string>
using namespace std;

class Card
{
public:
    Card(int cardSuit = 0, int cardValue = 2); //constructor will create a two of hearts by default
    ~Card(void);
    int getSuit(); //returns the suit of the Card
    int getValue(); //returns the value of the Card
    int getColor(); //returns the color of the Card
    friend ostream& operator<< (ostream &out, Card &cCard);

private:
    int suit; //card suit
    int value; //card value
    int color; //card color
} card;

#endif 

还有我的Deck.h

#pragma once

#ifndef DECK_H
#define DECK_H

#include "Card.h"
#include <vector>
using namespace std;

class Deck
{
public:
     Deck(void);
    ~Deck(void);
    void newDeck(); //regenerates the full 52 card deck (e.g. cards are missing)
    void shuffle(); //shuffles the deck
    int cardsInDeck(); //returns the number of cards remaining in the deck
    Card takeTopCard(); //returns the top card and removes it from the deck
private:
    vector<Card> myDeck; //vector of 52 Card objects that make up the deck
} deck;

#endif

这可能很明显,但我就是想不通......

根据要求,这是 Card.cpp:

#include "Card.h"

Card::Card(int cardSuit, int cardValue)
{
card.suit = cardSuit;
card.value = cardValue;
if(cardSuit == 0 || cardSuit == 1) card.color = 0;
if(cardSuit == 2 || cardSuit == 3) card.color = 1;
}

//returns the card's color
int Card::getColor() 
{
return card.color;
}

//returns the card's suit
int Card::getSuit()
{
return card.suit;
}

//returns the card's value
int Card::getValue()
{
return card.value;
}

这是我为测试它们而写的东西:

#include "Deck.h"

int main() 
{
Deck testDeck = *new Deck();
Card testCardCreation = *new Card();
Card testCard = testDeck.takeTopCard();
testDeck.shuffle();
Card testShuf = testDeck.takeTopCard();
cout << testCard << endl << testShuf << endl;

return 0;
}

最佳答案

对象 carddeck 在 header 中定义。当您将 header 包含到翻译单元中时,它将创建该对象的另一个定义。您可能应该只从类定义中删除 carddeck。如果您确实需要定义这些对象,您可以使用

extern Card card;

关于c++ - 使用#pragma once 和#ifndef 时 VS 2010 C++ LNK2005 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14097033/

相关文章:

c++ - A类的定义需要B类的定义,如何在不暴露B定义的情况下暴露A的公共(public)函数?

包含全局函数时的c++错误lnk2005

c++ - 具有非模板基的模板化类给我一个 LNK2005 错误

c++ - LNK2005(已定义)找不到错误

c++ - 使用 Cereal 反序列化 JSON 字符串

c++ - 捕获并格式化 cout

c++ - Leetcode-167:两个和II-输入数组已排序

c++ - 有没有更好的方法可以编写这个程序?