2015-04-12 44 views
0

我开始在我的电脑上建立一个项目。该项目编译在我的电脑上,但是当我将它复制到另一台电脑时,它有致命的错误(它在visual C++ express 2010上的工作)。它仍然很小,所以我会复制所有的项目。C++错误LNK2005和错误LNK1169

源文件 - >main.cpp中:

#include <iostream> 
#include <string> 
using namespace std; 
#include "List.h" 
void products_menu(){ 
    return; 
} 
void stores_menu(){ 
    return; 
} 
void costumers_menu(){ 
    return; 
} 
int main(){ 
    int option; 
    Products a; 
    do{ 
     cin>>option; 
     if(option==1) 
      products_menu(); 
      //option funcion 
     if(option==2) 
      stores_menu(); 
      //option funcion 
     if(option==3) 
      costumers_menu(); 
      //option funcion 
    }while(option!=4); 
} 

源文件 - >List.cpp:

#include <iostream> 
#include <string> 
using namespace std; 
#include "List.h" 
void products_menu(){ 
    return; 
} 
void stores_menu(){ 
    return; 
} 
void costumers_menu(){ 
    return; 
} 
int main(){ 
    int option; 
    Products a; 
    do{ 
     cin>>option; 
     if(option==1) 
      products_menu(); 
      //option funcion 
     if(option==2) 
      stores_menu(); 
      //option funcion 
     if(option==3) 
      costumers_menu(); 
      //option funcion 
    }while(option!=4); 
} 

头文件 - >List.h:

#pragma once 
#ifndef LIST_H 
#define LIST_H 
#include <string> 
using namespace std; 

class Products{ 
    private: 
     typedef struct node{ 
      int id; 
      string name; 
      int price; 
      node* next; 
     }; 
     //typedef struct node* nodePtr; 
     //nodePtr head; 

    public: 
     Products(); 
     //~Products(); 
     void addProduct(int id, string& name, int price); 
     void updateNameProduct(int id, string& oldName, string& newName); 
     void updatePriceProduct(int id, int oldPrice, int newPrice); 
     void printProducts();// 
    }; 
Products* first; 
Products* nodePtr; 
#endif 

,这是它给我的错误:在List.obj
已定义 “类产品* NODEPTR”(NODEPTR @@ 3PAVProducts @@?A) 错误LNK2005:

错误LNK2005“类产品*第一“在List.obj
错误LNK1169已经定义(第一@@ 3PAVProducts @@?A):一个或多个多重定义符号找到

+0

我发现它的工作,当我采取产品*第一;产品* nodePtr;线。但为什么它不与他们合作? –

+0

在头文件中声明'Products * first;'和Products * nodePtr;'作为'extern',并在'List.cpp'中声明一次。 –

+0

只是需要思考的一件事:您的树函数不返回任何内容,但每个函数都有一个返回语句作为其唯一内容。然后,你有一个函数返回一个整数,但没有任何返回语句。然后,检查出https://stackoverflow.com/questions/8646421/using-extern-keyword-to-declare-variables-in-header-files-c –

回答

0

如果必须使用全局变量(这通常是一个坏主意),然后你不能在标题中定义它们。他们受制于一个定义规则,所以只能在一个源文件中定义。

声明它们的头:

extern Products* first; 

,并在源文件中定义他们:

Products* first; 

但它听起来就像你想要的东西更像是注释掉声明:一个指向第一个node,作为Products类的成员,没有奇怪的全局变量。