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();
}
运行结果