【C++】类的使用
2015-12-30 11:21
302 查看
本文不是来长篇大论来步步分析,类的概念。主要是写写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;
}
运行结果如下:
这个更符合类编程语言的思维。
在《【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;
}
运行结果如下:
这个更符合类编程语言的思维。
相关文章推荐
- C#调用C++ Dll 并且实现联调
- C语言缓冲区(缓存)详解
- C++开发人脸性别识别教程(1)——前瞻
- 指针和引用的区别
- const全局变量和局部变量
- C语言输出 编译器为变量分配的内存地址 %p
- c++动态内存开辟之 new 的三种形态
- 预编译头文件来自编译器的早期版本,或者预编译头为 C++ 而在 C 中使用它(或相反)
- C语言的函数类型
- C++中异常处理
- C++多态之继承7-多重继承
- C语言宏定义使用技巧
- C语言宏定义和宏定义函数
- Flume thrift source C++ Demo
- Keil STM32 C++混合编程要点
- C++强制类型转换
- C++ namespace + std::bind std::function
- 5、vc++设置Excel颜色
- GDB 调试
- C语言:二叉树的中序遍历