本文不是来长篇大论来步步分析,类的概念。主要是写写C++对类的常见使用方式。纠正几个错误概念。
在《【C++】C++的输入输出、循环、条件、字符串、数组、类、继承的使用实例》(点击打开链接),由于不自觉地将Java等其它编程语言对类的经验迁移过来,对类的使用写成如下的形式:
#include <iostream>
#include <string>
using namespace std;
class Student{
public:
int no;
void setName(string name){
this->name=name;
}
string getName(){
return this->name;
}
private:
string name;
};
int main(){
Student stu2;
stu2.setName("dddd");
cout<<stu2.getName()<<endl;
getchar();
return 0;
}
上述代码,运行结果如下:
虽然运行是可以运行的,看起来也符合一般代码的写作要求,然而,如果这样写,以后就无法像Java等其它编程语言,使用Student stu2=new Student();来清空stu2这个Student实例。
实际上,一般情况下,在C++操作类,初始化一个类实例,更倾向使用一个类指针,指向一个new Student();,然后用->符号操作里面的东西。
这个类指针,实质上可以看作这个类的实例。正如在C语言,你可以将char*或者char[]看作string一样。
上述代码,应该写成这个样子:
#include <iostream>
#include <string>
using namespace std;
class Student{
public:
int no;
void setName(string name){
this->name=name;
}
string getName(){
return this->name;
}
private:
string name;
};
int main(){
Student *stu=new Student();
stu->setName("sssss");
cout<<stu->getName()<<endl;
getchar();
return 0;
}
运行结果如下:
这个更符合类编程语言的思维。