这是我在阅读Effective c++中认为比较重要的部分,下面给出了我对这一节的理解,并写出对应的比较容易理解的代码。
当模板没有遇到继承时,下例可以编译通过。
class companyA {
public:
void sendCleartext() {
cout << "1" << endl;
}
void sendEncrypted() {
cout << "2" << endl;
}
};
template<typename Company>
class MsgSender {
public:
void sendClear(const string& info) {
cout << info << endl;
Company c;
c.sendCleartext();
}
void sendSecret(const string &info){
cout << info << endl;
Company c;
c.sendEncrypted();
}
};
而当遇到继承时,会遇到编译不通过的错误。(实际上VS2015编译通过,DEV C++编译不通过),代码如下,因为编译器知道基类模板可能被特化,而那个特化的版本可能不会提供和一般性template相同的接口。因为它往往拒绝在模板化基类(本例MsgSender)寻找继承来的名称。
class companyA {
public:
void sendCleartext() {
cout << "1" << endl;
}
void sendEncrypted() {
cout << "2" << endl;
}
};
template<typename Company>
class MsgSender {
public:
void sendClear(const string& info) {
cout << info << endl;
Company c;
c.sendCleartext();
}
void sendSecret(const string &info){
cout << info << endl;
Company c;
c.sendEncrypted();
}
};
template<typename Company>
class LoggingMsgSender :public MsgSender<Company> {
void sendClearMsg(string&info) {
sendClear(info);
}
void sendSecretMsy(string&info) {
sendSecret(info);
}
};
有三种方法可以解决这个问题:
1:使用this-> 。本例this->sendClear(info);
2: using,, 本例 using MsgSender<Company>::sendClear;
3:显示调用 ,MsgSender<Company>::sendClear(info);
请记住:
可在继承类内通过this-> 指出基类中的成员名称,或由资格修饰符完成。