用C++写代码:将下列程序分离类定义和主函数,改成多文件结构。主函数使用类的方式采取包含类定义的头文件的方法。写出运行结果。#include <iostream> using namespace std; class Cat { public: int GetAge(); void SetAge(int age); void Meow(); //喵喵叫 protected: int itsAge; }; int Cat::GetAge() { return itsAge; } void Cat::SetAge(int age) { itsAge = age; } void Cat::Meow() { cout<<"Meow.\n"; } int main() { Cat frisky; frisky.SetAge(5); frisky.Meow(); cout<<"frisky is a cat who is " <<frisky.GetAge() <<" years old.\n"; frisky.Meow(); }
时间: 2023-06-25 17:02:55 浏览: 195
C++ 文件结构_,详解
// Cat.h
#ifndef CAT_H
#define CAT_H
class Cat {
public:
int GetAge();
void SetAge(int age);
void Meow(); //喵喵叫
protected:
int itsAge;
};
#endif
// Cat.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";
}
// main.cpp
#include "Cat.h"
#include <iostream>
using namespace std;
int main() {
Cat frisky;
frisky.SetAge(5);
frisky.Meow();
cout << "frisky is a cat who is " << frisky.GetAge() << " years old.\n";
frisky.Meow();
return 0;
}
// 运行结果
// Meow.
// frisky is a cat who is 5 years old.
// Meow.
阅读全文