【C++】类的使用

本文不是来长篇大论来步步分析,类的概念。主要是写写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;
}

运行结果如下:


这个更符合类编程语言的思维。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值