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

运行结果

相关推荐
一个不知名程序员www3 小时前
算法学习入门 --- 哈希表和unordered_map、unordered_set(C++)
c++·算法
二哈喇子!3 小时前
BOM模型
开发语言·前端·javascript·bom
C++ 老炮儿的技术栈3 小时前
在C++ 程序中调用被 C编译器编译后的函数,为什么要加 extern “C”声明?
c语言·c++·windows·git·vscode·visual studio
二哈喇子!3 小时前
空指针异常
开发语言
咚为3 小时前
Rust Print 终极指南:从底层原理到全场景实战
开发语言·后端·rust
%xiao Q3 小时前
GESP C++五级-202406
android·开发语言·c++
Psycho_MrZhang3 小时前
Neo4j Python SDK手册
开发语言·python·neo4j
Traced back3 小时前
# C# + SQL Server 实现自动清理功能的完整方案:按数量与按日期双模式
开发语言·c#
Sarvartha3 小时前
C++ STL 栈的便捷使用
c++·算法
sin22013 小时前
MyBatis的执行流程
java·开发语言·mybatis