Visual Studio如何进行类文件的管理(类文件的分离)

大家好:

衷心希望各位点赞。

您的问题请留在评论区,我会及时回答。

一、分离式设计类

实际开发中,类的声明放在头文件中,给程序员看类的成员和方法。比如:Dog.h(类的声明文件)

类的成员函数的具体实现,保存在 .cpp 文件中。比如:Dog.cpp(类的方法文件)

其他文件,如果需要使用这个类,就包含这个类的头文件。比如:test.cpp

二、项目文件结构

一图胜千言,解释放后面:

类的声明 Dog.h 放在头文件目录中, 类的成员函数的实现放在源文件目录下的 Dog.cpp 文件中,test.cpp 是用来放测试代码的文件。

二、代码

1、Dog.h的代码

复制代码
#pragma once

#include <string>

using namespace std;

//类的声明文件
class Dog{
private:
	string name;
	int age;
public:
	Dog(string name, int age);
	void sleep();
	void eat();
	void say();
};

2、Dog.cpp的代码

复制代码
//类的具体实现:用来实现类Dog的具体方法

#include "Dog.h"
#include <iostream>
#include <string>

using namespace std;

Dog::Dog(string name, int age) {
	this->name = name;
	this->age = age;
}

void Dog::eat() {
	cout << "吃饭啦" << endl;
}

void Dog::sleep() {
	cout << "睡觉啦" << endl;
}

void Dog::say() {
	cout << this->name << endl;
	cout << this->age << endl;
}

3、test.cpp的代码

复制代码
#include <iostream>
#include "Dog.h"

using namespace std;

int main() {
	Dog dog("旺仔", 3);//创建Dog对象
	dog.eat();//输出 吃饭啦
	dog.sleep();//输出 睡觉啦
	dog.say();//输出 旺仔 3

	system("pause");
	return 0;
}

三、运行截图

四、总结

在使用 Visual Studio 开发项目的时候,学会进行"类文件的分离"十分重要。这会帮助开发者管理项目更加轻松。

实际开发中,类的声明放在头文件中,给程序员看类的成员和方法。比如:Dog.h(类的声明文件)

类的成员函数的具体实现,保存在 .cpp 文件中。比如:Dog.cpp(类的方法文件)

其他文件,如果需要使用这个类,就包含这个类的头文件。比如:test.h

相关推荐
VIP_CQCRE21 小时前
在 Visual Studio 里接入 Ace Data Cloud:让 IDE 拥有 OpenAI 兼容 AI 能力
openai·ai编程·开发工具·visual studio·ace data cloud
VIP_CQCRE1 天前
在 Visual Studio 里接入 Ace Data Cloud:让 LMLocal 调用统一的 OpenAI 兼容模型接口
ai·大模型·visual studio·ace data cloud·lmlocal
水饺编程2 天前
编程数学:三角函数基础01,直角三角函数
c语言·c++·windows·visual studio
水饺编程5 天前
第5章,[Win32 章节] :圆角矩形教学插图绘制程序
c语言·c++·windows·visual studio
沧海一笑-dj6 天前
【C++】Visual Studio 2026下载和安装
c++·visual studio·vs·vs2026
一直C7 天前
Linux网络编程|HTTP协议详解(报文、请求方法、状态码)
linux·http·wireshark·vim·visual studio
水饺编程7 天前
第5章,[Win32 章节] :练习程序,BigFontPic
c语言·c++·windows·visual studio
Lhan.zzZ8 天前
QML 组件库:VS2022 + Qt 静态库方案
开发语言·c++·qt·visual studio
一直C8 天前
Linux应用软件编程|TCP协议与Socket全套编程(三次握手、四次挥手、报文头部、核心机制)
linux·网络协议·tcp/ip·wireshark·vim·visual studio
水饺编程12 天前
第5章,[Win32 章节] :Polygon 函数和多边形填充模式
c语言·c++·windows·visual studio