我已经从书中复制出来了。我只是不确定要在main.cpp
源文件中添加什么才能使其运行。C++中的单独文件中的类?
我知道类声明进入.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)定义的末尾缺少“}”。) –
您收到的错误消息是什么? – Subhajit