定义抽象类
1
2
3
4
|
class Person { public : virtual void born() = 0; }; |
类的继承
1
2
3
4
5
6
|
class Man : public Person { public : void born() { cout << " 出生了一个男人" << endl; } }; |
使用new关键字实例化对象,只能用指针变量来接收
因此,在对象的实例化,作为函数的参数和返回值时,都用要使用指针
1
2
3
4
|
Person* generatePersion(Person* person1) { Person* person = new Man(); retrun person; } |
使用普通的对象属性及方法时使用.来引用,但是用指针表示的对象则使用->
1
2
3
4
|
Student stu1( "张三" ,18, "北京" ); // 直接用变量实例化对象 Student *stu2 = new Student( "李四" ,20, "上海" ); // 通过指针实例化对象 stu1.study(); stu2->study(); |
定义类的时候,属性需要赋初始值的请况
1
2
3
4
5
6
7
|
class StudentId { private : static StudentId* si; // 必须用static修饰 static string id; // 必须用static修饰 }; string StudentId::id = "20200001" ; StudentId* StudentId::si = NULL; |
类的前置声明
c++在使用这个类之前,必须要定义这个类,不然编译器不知道有这个类
因此,当两个类互相嵌套时,可能会报错,解决的方法就是使用前置声明
如果在类的方法实现过程中,还用到了另一个类的相关方法
那么最好是将类方法的定义和实现分开写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class AbstractChatroom; // 类的前置声明 class Member{ protected : AbstractChatroom *chatroom; // 使用之前必须先定义 void setChatroom(AbstractChatroom *chatroom) { // 类方法可以在类定义的时候就实现 this ->chatroom = chatroom; } void chatroom_play(); // 当方法内部需要使用到前置声明类中的方法时,只能先定义,后实现 }; class AbstractChatroom{ // 类的具体定义 public : Member member; // 类的相互嵌套 virtual void sendText(string from,string to,string message) = 0; void play(){ cout << "在聊天室里玩耍!" << enld; } }; void Member::chatroom_play(){ // 类方法的具体实现 chatroom -> play(); } |
命名空间的使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
#include <iostream> using namespace std; namespace my_namespace{ // 定义命名空间 class Student{ // 命名空间中的对象 public : string name; int age; string home; Student(string name, int age, string home); string getName(); int getAge(); string getHome(); void setName(string name); void setAge( int age); void setHome(string home); }; Student::Student(string name, int age, string home){ this -> name = name; this -> age = age; this -> home = home; } string Student::getName(){ return name; } int Student::getAge(){ return age; } string Student::getHome(){ return home; } void Student::setName(string name){ this -> name = name; } void Student::setAge( int age){ this -> age = age; } void Student::setHome(string home){ this -> home = home; } } // 使用命名空间,方法1 using namespace my_namespace; int main(){ Student *stu1 = new Student( " 张三" , 18, "北京" ); cout << stu1 -> getName() << endl; } // 使用命名空间,方法2 int main(){ my_namespace::Student *stu1 = new my_namespace::Student( " 张三" , 18, "北京" ); cout << stu1 -> getName() << endl; } |
总结
到此这篇关于C++对象与继承使用中一些问题介绍的文章就介绍到这了,更多相关C++对象与继承内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_37428140/article/details/122265061