C++ 无法从 main.cpp 中的另一个文件实例化一个类

Chr*_*ian 0 c++ linker class

我不能让它工作

地址

#ifndef ADDR_H
#define ADDR_H

class Foo{
public:
  Foo();                  // function called the default constructor
  Foo( int a, int b );    // function called the overloaded constructor
  int Manipulate( int g, int h );

private:
  int x;
  int y;
};

#endif
Run Code Online (Sandbox Code Playgroud)

地址文件

#include "addr.h"


Foo::Foo(){
  x = 5;
  y = 10;
}
Foo::Foo( int a, int b ){
  x = a;
  y = b;
}

int Foo::Manipulate( int g, int h ){
  return x = h + g*x;
}
Run Code Online (Sandbox Code Playgroud)

主程序

#include "addr.cpp"

int main(){
    Foo myTest = Foo( 20, 45 );
    while(1){}
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我收到这些链接器错误:

错误 LNK2005: "public: int __thiscall Foo::Manipulate(int,int)" (?Manipulate@Foo@@QAEHHH@Z) 已在 addr.obj c:\Users\christian\documents\visual studio 2010\Projects\ 中定义控制台测试\控制台测试\main.obj

错误 LNK2005: "public: __thiscall Foo::Foo(int,int)" (??0Foo@@QAE@HH@Z) 已在 addr.obj c:\Users\christian\documents\visual studio 2010\Projects\ 中定义控制台测试\控制台测试\main.obj

错误 LNK2005: "public: __thiscall Foo::Foo(void)" (??0Foo@@QAE@XZ) 已在 addr.obj c:\Users\christian\documents\visual studio 2010\Projects\Console Test\Console 中定义测试\main.obj

错误 LNK1169:找到一个或多个多重定义的符号 c:\users\christian\documents\visual studio 2010\Projects\Console Test\Release\Console Test.exe

我将不胜感激任何形式的帮助!!!

Naw*_*waz 5

#include "addr.cpp"
Run Code Online (Sandbox Code Playgroud)

您将 .cpp 文件包含到您的 .cpp 文件中main.cpp,这就是导致问题的原因。您应该改为包含头文件,如:

#include "addr.h"  //add this instead, to your main.cpp
Run Code Online (Sandbox Code Playgroud)

因为它是包含类定义的头文件Foo