C++面向对象编程学生类案例

C++面向对象编程,学生类案例

采用引用std简化

cpp 复制代码
#include <string.h>
#include <iostream>
using namespace std;

class Student{
	private:
		string name ;
		int age;
		string classname ;
	public:
		Student(string name,int age,string clsname ){
			this->age=age;
			this->name=name;
			this->classname=clsname;
		};
		Student(){
			this->age=18;
			this->name="susan";
			this->classname="2331";
		};
	
		void setName(string name){
			 this->name=name;
		};
		void show(){
		  cout<<"student name is "<<this->name+" classname"<<this->classname<<endl;
		};
		string getName(){
		   return this->name;	
		};
		
};

int main(){
	
	Student *s,s1("Lily",20,"2031");
   	s=new Student("Xiaoming",21,"2231");
    s->show();
    s= &s1;
    s->show();    
	s1.show();
	cout<< s->getName();
				
}
		
		
cpp 复制代码
//方案1,std采用静态类调用
#include <string.h>
#include <iostream>


class Student{
	private:
		std::string name ;
		int age;
		std::string classname ;
	public:
		Student(std::string name,int age,std::string clsname ){
			this->age=age;
			this->name=name;
			this->classname=clsname;
		};
		Student(){
			this->age=18;
			this->name="susan";
			this->classname="2331";
		};
	
		void setName(std::string name){
			 this->name=name;
		};
		void show(){
		  std::cout<<"student name is "<<this->name+" classname"<<this->classname<<std::endl;
		};
		std::string getName(){
		   return this->name;	
		};
		
};

int main(){
	
	Student *s,s1("Lily",20,"2031");
   	s=new Student;
    s->show();
    s= &s1;
    s->show();    
	s1.show();
	std::cout<< s->getName();
				
}
		
		

运行结果

相关推荐
MessiGo10 分钟前
Javascript 编程基础(5)面向对象 | 5.1、构造函数实例化对象
开发语言·javascript·原型模式
大霞上仙14 分钟前
nonlocal 与global关键字
开发语言·python
曦月逸霜16 分钟前
第34次CCF-CSP认证真题解析(目标300分做法)
数据结构·c++·算法
galaxy_strive19 分钟前
绘制饼图详细过程
开发语言·c++·qt
黑客老李1 小时前
JavaSec | SpringAOP 链学习分析
java·运维·服务器·开发语言·学习·apache·memcached
开开心心就好1 小时前
高效Excel合并拆分软件
开发语言·javascript·c#·ocr·排序算法·excel·最小二乘法
特立独行的猫a1 小时前
Nuxt.js 中的路由配置详解
开发语言·前端·javascript·路由·nuxt·nuxtjs
勤奋的知更鸟2 小时前
Java编程之原型模式
java·开发语言·原型模式
Unpredictable2222 小时前
【VINS-Mono算法深度解析:边缘化策略、初始化与关键技术】
c++·笔记·算法·ubuntu·计算机视觉
珂朵莉MM2 小时前
2021 RoboCom 世界机器人开发者大赛-高职组(初赛)解题报告 | 珂学家
java·开发语言·人工智能·算法·职场和发展·机器人