如何使子类构造函数像其超类一样繁琐地行动?

如何使子类构造函数像其超类一样繁琐地行动?

问题描述:

看到我们有以下课程:

see we have the following class:

class CText : public string
{
    CText();
    ~CText();
}



如你所知,C ++中的string类有几个版本的构造函数。现在我希望我的CText类的行为方式如下:


As you know, the class "string" in C++ has several version of constructors. Now I'd like my CText class to behave in such manners as follow:

CText text("foo");
string str = "another foo :-)";
CText text2(str);
.
.
.



如何定义构造函数?


How do I define my constructors?

与定义相同的方式他们换了新课;检查 string 的文档,看看存在什么构造函数,并提供相同的。
The same way you would define them for a new class; check the documentation for string to see what constructors exist, and provide the same.


理查德的答案是正确的,但值得一提如何去做。



例如,字符串类有一个构造函数 string(char * str)

然后,您将使用相同的构造函数定义您的类,并按如下方式调用基类构造函数:

Richard's answer is correct, but it is worth mentioning how to go about it.

For example, the string class has a constructor string(char *str).
Then you would define your class with the same constructor, and call the base class constructor as follows:
class CText : public string
{
    CText(char *str) : string(str) { } //This calls the base class constructor
    //more constructors and other functions
}


如果你可以依赖C ++ 11,一个简单的方法可以是

If you can rely on C++11, a simple way can be
class CText: public string
{
public:
    template<class... T>
    CText(T&&... t) :string(forward<T>(t)...) 
    {}

    ...
};



本质上,构造函数基于一个varadic模板(从0到任意类型的任意数量的参数)以r值引用为基础(认为它是一个放松的 const& ,它也可以采取和修改临时值)并转发(在C ++ 0x中一个&& 在作为参数传递时变为& forward ,只需将其强制转换为&& )与基类一对一。



结果,直到有字符串中的构造函数,它接受某些参数,它们也可以被超类占用。


Essentially the constructor is based on a varadic template (taking form 0 to whatever number of argument of whatever types) that are taking in term of r-value reference (think to it as a relaxed const&, that can also take and modify temporary values) and forwarded (in C++0x a && becomes a & when passed as argument: forward, just casts it back to &&) one-to-one to the base class.

As a result, until there is a constructor in string that takes certain parameters, They can be taken by the superclass as well.