C++ 基础 类 属性和方法

面向对象的思想就不在这阐述了 

现在我们需要定义一个Student 类 并定义类的属性和方法 这里用的是VS2012 当然 最好用的是Qt 后期可能会换 

这里说一下如何用VS来创建一个C++对象类 定义属性和方法  并在Main里调用

1)新建一个类 并点击右下方添加 会出现一个向导 只要录入类名 就会创建后面的一系列文件

2)创建了一个Student.h和 和 cpp

3).h文件 需要定义 类的属性 和声明方法 

#pragma once
#include <string>
#include <iostream>
 
using namespace std;
class Student
{
public:
	Student(void);
	~Student(void);
	void set_data( int n,  string p, string s );
	void display();
private:
	int num;
	string name;
	string sex;
};

4)cpp文件 实现 方法体内容

#include "stdafx.h"
#include "Student.h"


Student::Student(void)
{

}


Student::~Student(void)
{
}
void Student::set_data( int n,  string p, string s )
{
	num =n;
	name= p;
	sex=s;
}
void Student::display()
{
	cout<< num<<" "<<name<<" "<< sex<<endl;
}

5)Main 窗体需要引用 .h文件

 #include "Student.h"
	Student stu1,stu2;

	stu1.set_data(29,"大飞","男");
	stu2.set_data(19,"小非","女");
	stu1.display();
	stu2.display(); 
	system("pause");

6)输出效果

发布了279 篇原创文章 · 获赞 43 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/q465162770/article/details/103470957