0
点赞
收藏
分享

微信扫一扫

❥关于C++之私有继承

金刚豆 2022-03-17 阅读 72

私有继承是C++另一种实现has-a(包含)关系的途径。使用私有继承,基类的公有成员和保护成员都将成为派生类的私有成员。这意味着基类方法将不会成为派生对象公有接口的一部分,但可以在派生类的成员函数中使用它们。

下面,我们用Student类私有继承标准库中的std::string类:

// studenti.h -- defining a Student class using private inheritance
#include <iostream>
#include <string>
class Student : private std::string {
public:
Student() : std::string("Null Student") {}
bool HaveMyCountry(const std::string& str) const;
void Append(const std::string
const std::string& Name() const;
friend std::istream& operator>>(std::istream & is, Student
};
// studenti.cpp -- Student class using private inheritance
#include "studenti.h"
using std::istream;
using std::string;
bool Student::HaveMyCountry(const string& str) const {
if (string::size() > 0) {
std::size_t found = string::find(str);
if (found != std::string::npos)
return true;
}
return false;
}
void Student::Append(const std::string& str) {
string::append(str);
}
const string& Student::Name() const {
return (const string
}
istream& operator>>(istream& is, Student& stu) {
is >> (string
return is;
}
// use_stui.cpp -- using a class with private inheritance
// compile with studenti.cpp
#include <iostream>
#include "lacks.h"
using std::cin;
using std::cout;
using std::endl;
const int SIZE = 3;
const std::string MY_COUNTRY = "China";
int main() {
Student stuArr[SIZE] = { Student(), Student(), Student() };
cout << "Please enter the country's name: ";
for (int i = 0; i < SIZE; i++) {
cin >> stuArr[i];
}
for (int i = 0; i < SIZE; i++) {
Student stu = stuArr[i];
cout << stu.Name() << " contains my country name:" << (stu.HaveMyCountry(MY_COUNTRY) ? "Yes" : "No") << endl;
}
stuArr[SIZE -1].Append(MY_COUNTRY);
cout << "After do an append to the last country: " << endl;
cout << stuArr[SIZE -1].Name() << " contains my country name:" << (stuArr[SIZE -1].HaveMyCountry(MY_COUNTRY) ? "Yes" : "No") << endl;
return 0;
}
Please enter the country's name: |AmericanMan ChinaBank RussiaBeer<Enter>
AmericanMan contains my country name:No
ChinaBank contains my country name:Yes
RussiaBeer contains my country name:No
After do an append to the last country:
RussiaBeerChina contains my country name:Yes

私有继承使得能够使用类名和作用域解析运算符来调用基类的公有方法。

对于继承类,代码中构造函数将使用成员初始化列表语法,它使用类名而不是成员名来标识构造函数:

Student() : std::string("Null Student") {}

Student类的默认构造函数调用了基类std::string类的构造函数:string (const char* s); 以完成基类成员的初始化。

派生类使用了基类的公有方法size()、find()、append()和公有静态成员常量npos。私有继承也是可以调用基类的公有成员和方法的,不同于公有继承的是,要使用类名和作用域解析运算符来调用,正如代码中看到的那样。

要使用基类对象本身,该如何做呢?使用私有继承时,该string对象没有名称。答案是使用强制类型转换,正如代码中看到的那样。由于Student类是从string类派生而来的,因此可以通过强制类型转换,将Student对象转换为string对象;结果为继承而来的string对象。

举报

相关推荐

0 条评论