温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++对象与继承使用的问题有哪些

发布时间:2022-01-04 08:55:13 来源:亿速云 阅读:147 作者:iii 栏目:开发技术

本篇内容主要讲解“C++对象与继承使用的问题有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++对象与继承使用的问题有哪些”吧!

定义抽象类

class Person {
public:
	virtual void born() = 0;
};

类的继承

class Man :public Person {
public:
	void born() {
		cout << " 出生了一个男人" << endl;
	}
};

使用new关键字实例化对象,只能用指针变量来接收

因此,在对象的实例化,作为函数的参数和返回值时,都用要使用指针

Person* generatePersion(Person* person1) {
	Person* person = new Man();
	retrun person;
}

使用普通的对象属性及方法时使用.来引用,但是用指针表示的对象则使用->

Student stu1("张三",18,"北京");  // 直接用变量实例化对象
Student *stu2 = new Student("李四",20,"上海");  // 通过指针实例化对象
stu1.study();
stu2->study();

定义类的时候,属性需要赋初始值的请况

class StudentId {
private:
	static StudentId* si;  // 必须用static修饰
	static string id;  // 必须用static修饰
};
string StudentId::id = "20200001";
StudentId* StudentId::si = NULL;

类的前置声明

c++在使用这个类之前,必须要定义这个类,不然编译器不知道有这个类
因此,当两个类互相嵌套时,可能会报错,解决的方法就是使用前置声明
如果在类的方法实现过程中,还用到了另一个类的相关方法
那么最好是将类方法的定义和实现分开写

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();
}

命名空间的使用

#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++对象与继承使用的问题有哪些”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI