gpt4 book ai didi

c++ - 继承:类字符串

转载 作者:行者123 更新时间:2023-11-30 03:50:04 25 4
gpt4 key购买 nike

我遇到了一项家庭作业,它需要一个名为 string_extend 的自建类,该类继承自类 string。下面的string_extend类是我的代码,main()部分是作业要求的部分。

class string_extend:public string{
public:
string_extend(const string& str):string(str){}

};
int main(){
string_extend a("amd");
string_extend b(a);
cout<<a<<b;
}

谁能给出任何关于如何从类 string 继承所有函数的提示?

最佳答案

Could anyone give any hint about how to inherit all the functions from class string?

您的代码已经这样做了。但是,您的 main 没有使用任何 string 的成员函数;它使用非继承的构造函数,除非您以其他方式告诉编译器(见下文)。

为了使用基类的构造函数,您需要在派生类中定义一个具有相同签名的构造函数。您为采用 string& 的构造函数执行了此操作,但没有为您的 main 使用的其他构造函数执行此操作。

在 C++03 中,它是按照您对第一个构造函数所做的方式完成的,即

string_extend(const char* str):string(str){}

demo 1.

在 C++11 中你可以 inherit constructors :

class string_extend:public string{
public:
using string::string;
};

demo 2.

关于c++ - 继承:类字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32033752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com