问题描述:

// Use multiple inheritance. We want

// both a string and an Object:

class MyString: public string, public Object {

public:

~MyString() {

cout << "deleting string: " << *this << endl;

}

MyString(string s) : string(s) {}

};

For the above code, I do not understand what string(s) mean? There is no variable called string in fact, but why it can work?

网友答案:

Usually, when constructing a derived class, the default base-constructor (if it exists) will be called. If you want to explicitly call a different base-constructor for a certain derived-constructor, you can do this using the initializer list.

In this case, when constructing MyString, the string-constructor which takes a string as its only argument (the copy constructor), will be called with s as the argument.

网友答案:

The string(s) is constructing the parent class instance of MyString with s.

Note that MyString inherits from string, this is what that use of string refers to.

This is known as an "initializer list".

网友答案:

It initialises the parent subobject of type string. In effect, it specifies which parent constructor to call for the string parent.

网友答案:

MyString derives from string. The syntax you refer to, string(s), calls the base class constructor with s as the sole argument.

相关阅读:
Top