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

运行结果

相关推荐
一行代码一行诗++9 分钟前
C语言中scanf详解
c语言·开发语言
凤山老林11 分钟前
26-Java this 关键字
java·开发语言
啊我不会诶17 分钟前
2024ICPC西安邀请赛补题
c++·算法
ZenosDoron17 分钟前
keil软件修改字体,Asm editor,和C/C++ editor的区别
c语言·开发语言·c++
山栀shanzhi39 分钟前
C/C++之:构造函数为什么不能设置为虚函数?
开发语言·c++·面试
lsx20240640 分钟前
.toggleClass() 方法详解
开发语言
谭欣辰1 小时前
C++ 版Dijkstra 算法详解
c++·算法·图论
yuan199971 小时前
C&CG(列与约束生成)算法,来解决“风光随机性”下的微网鲁棒配置问题
c语言·开发语言·算法
李白的天不白1 小时前
读到数据为undefind是的几种情况
开发语言·javascript·ecmascript
LeocenaY1 小时前
C语言面试题总结
c语言·开发语言·数据结构