1

我已经环顾了一个多小时,但找不到任何对我的处境有益的东西。我是 C++ 的初学者,这是我第一次尝试将代码拆分为两个 .cpp 文件和一个 .h 文件。我还没有遇到任何成功。这是我的代码:

#include "stdafx.h"
#include <iostream>
#include "Cat.h"
using namespace std;
int main()
{
   Cat Frisky; // declare variable of type Cat, creates an object
   Frisky.SetAge( 5 ); // put value INTO object
   Frisky.Meow( ); // make object do something
   std::cout << "Frisky is a cat who is " ;
   std::cout << Frisky.GetAge() << " years old.\n " ;
   Frisky.Meow( ); // make object do something
   return 0;
}

// This is my cat.h
class Cat {

public:
   int GetAge();                        // accessor
   void SetAge( int age ); // accessor
   void Meow();         // general function

private:
   int itsAge;     // member variable

};

#include "Cat.h"
int Cat::GetAge( )
{
   return itsAge;

} // end function GetAge

// set function, PUT VALUE IN to the object
void Cat::SetAge( int age )
{
   itsAge = age ;

} // end function SetAge

// What do Cats do?

// What action should a Cat object perform?
void Cat::Meow( )
{
   std::cout << "Meow.\n";

} // end function Meow

这是我一个多小时以来一直遇到的错误消息。

1>------ Build started: Project: TestCat, Configuration: Debug Win32 ------
1>  TestCat.cpp
1>TestCat.obj : error LNK2019: unresolved external symbol "public: int __thiscall Cat::GetAge(void)" (?GetAge@Cat@@QAEHXZ) referenced in function _main
1>TestCat.obj : error LNK2019: unresolved external symbol "public: void __thiscall Cat::Meow(void)" (?Meow@Cat@@QAEXXZ) referenced in function _main
1>TestCat.obj : error LNK2019: unresolved external symbol "public: void __thiscall Cat::SetAge(int)" (?SetAge@Cat@@QAEXH@Z) referenced in function _main
1>C:\Documents and Settings\Geena\Desktop\TestCat\Debug\TestCat.exe : fatal error LNK1120: 3 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我将 Cat.cpp 文件和 Cat.h 文件放入以下目录:C:\Documents and Settings\Geena\Desktop\TestCat\TestCat

只是在寻找让这个该死的程序启动并运行的答案。

谢谢你

4

1 回答 1

1

我强烈建议您在下一个问题之前休读本教程

猫.h

class Cat {
public:
    int GetAge();                      
    void SetAge( int age ); 
    void Meow(); 
private:
    int itsAge;  
};

猫.cpp

#include "cat.h"
#include <iostream>

using namespace std;

int Cat::GetAge(){return itsAge;}
void Cat::SetAge(int age){itsAge = age ;}
void Cat::Meow(){cout << "Meow.\n";} 

主文件

#include "cat.h"
#include <iostream>

using namespace std;

int main()
{
   Cat Frisky; 
   Frisky.SetAge(5);
   Frisky.Meow(); 
   cout << "Frisky is a cat who is " ;
   cout << Frisky.GetAge() << " years old.\n " ;
   Frisky.Meow( );
   system("pause");
   return 0;
}
于 2013-02-21T09:51:12.537 回答