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();
				
}
		
		

运行结果

相关推荐
小坏坏的大世界1 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
wjs20242 小时前
状态模式(State Pattern)
开发语言
我命由我123452 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
liulilittle2 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
励志要当大牛的小白菜4 小时前
ART配对软件使用
开发语言·c++·qt·算法
PAK向日葵5 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱装代码的小瓶子6 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
Maybe_ch7 小时前
.NET-键控服务依赖注入
开发语言·c#·.net
超浪的晨7 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
终焉暴龙王7 小时前
CTFHub web进阶 php Bypass disable_function通关攻略
开发语言·安全·web安全·php