【问题标题】:Classes in separate files in C++?C ++中单独文件中的类?
【发布时间】:2013-02-08 09:06:27
【问题描述】:

我从书中复制了这个。我只是不确定在main.cpp 源文件中添加什么以使其运行。

我知道类声明放在.h 文件中,实现放在.cpp 文件中。我需要在main.cpp 中写什么?

我尝试了很多不同的方法,但我收到的错误消息太多了。

 // cat.h
#ifndef ____2_cat_implementation__Cat__
#define ____2_cat_implementation__Cat__

#include <iostream>
using namespace std;
class Cat
{
public:
Cat (int initialAge);
~Cat();
int GetAge() { return itsAge;}              
void SetAge (int age) { itsAge = age;}      
void Meow() { cout << "Meow.\n";}          
private: int itsAge;
};

#endif /* defined(____2_cat_implementation__Cat__) */

...

// cat.cpp
#include <iostream>
#include "Cat.h"
using namespace std;

Cat::Cat(int initialAge) 
{
itsAge = initialAge;
}

Cat::~Cat() 
{

}

int main()
{
    Cat Frisky(5);
    Frisky.Meow();
    cout << "Frisky is a cat who is ";
    cout << Frisky.GetAge() << " years old.\n";
    Frisky.Meow();
    Frisky.SetAge(7);
    cout << "Now Frisky is " ;
    cout << Frisky.GetAge() << " years old.\n";
    return 0;
}

【问题讨论】:

  • 你是如何编译的?您收到的前几条错误消息是什么? (很多潜在问题 - 例如,在区分大小写的文件系统上,Cat.h 找不到名为 cat.h 的文件,在 Cat::Cat(int) 定义的末尾缺少“}”。)
  • 您收到的错误信息是什么?

标签: c++ oop class


【解决方案1】:

再看这部分:

Cat::Cat(int initialAge); 
{
itsAge = initialAge;

Cat::~Cat() 

您缺少构造函数的结束},以及函数头后的额外;

在不相关的说明中,不要使用以下划线开头的全局名称(如____2_cat_implementation__Cat__),这些名称由规范保留。

【讨论】:

    【解决方案2】:

    您缺少} 和不必要的;

      //----------------------v
      Cat::Cat(int initialAge); 
      {
          itsAge = initialAge;
      }
    //^
    

    我需要在 main.cpp 中写什么

    通常,正如您所指出的,.h 文件包含声明,.cpp 文件 - 定义。然后,main.cpp 文件应该包含main 函数(不必命名文件,包含main 函数main.cpp。它可以是任何东西。

    因此,在您的示例中,您可以创建一个具有以下内容的main.cpp 文件:

    // include the declarations file
    #include "cat.h"
    
    // include the header for cin/cout/etc
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        Cat Frisky(5);
        Frisky.Meow();
        cout << "Frisky is a cat who is ";
        cout << Frisky.GetAge() << " years old.\n";
        Frisky.Meow();
        Frisky.SetAge(7);
        cout << "Now Frisky is " ;
        cout << Frisky.GetAge() << " years old.\n";
        return 0;
    }
    

    其他说明:

    • using namespace std; 是不好的做法,尤其是在头文件中。请改用std::(例如,std::coutstd::cinstd::string 等)
    • 因为你有.h.cpp 文件,所以不要把一半的实现放在头文件中,其余的放在源文件中。将所有定义放在源文件中(除非你想inline 函数,在头文件中实现)
    • 避免使用以___ 开头的名称 - 它们由标准保留。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多