![](/img/trans.png)
[英]Inheritance and template in C++: Why doesn't the following piece of code compile?
[英]Why will the following code not compile (inheritance in c++)
所以这不是关于我面临的问题,而是关于考试中我无法正确回答的问题。
我有以下课程:
template<class T>
class Server {
protected:
std::vector<T> requests;
public:
Server() = default;
Server(const Server& other) = default;
~Server() = default;
Server(const std::vector<T>& vec);
Server& operator=(const Server<T>& other) = default;
Server& operator+=(const T& request);
Server& operator-=(const T& request);
void operator()();
std::size_t numRequests() const;
friend Server<T> operator+(const Server<T>& a, const Server<T>& b );
friend std::ostream& operator<<(std::ostream&, const Server<T>&);
};
template<class T>
Server<T> operator+(const Server<T>& a, const Server<T>& b );
template<class T>
std::ostream& operator<<(std::ostream&, const Server<T>&);
现在,我创建了一个名为LimitedNamedServer
的类,这些类之间的区别在于LimitedNamedServer
对象具有最大请求容量和名称。
这是它的样子:
template<class T>
LimitedNamedServer : public Server<T> {
std::string name;
std::size_t maxLimit;
public:
LimitedNamedServer(const char* name, std::size_t limit) : Server<T>(), name(name), maxLimit(limit) {}
LimitedNamedServer(const LimitedNamedServer& other) = default;
~LimitedNamedServer() = default;
LimitedNamedServer(const char* name, std::size_t limit, const std::vector<T>& vec) : Server<T>(vec), name(name), maxLimit(limit) {
if(requests.size() > maxLimit) {
throw OverLimit();
}
}
LimitedNamedServer& operator=(const LimitedNamedServer<T>& other) = default;
LimitedNamedServer& operator+=(const T& request) {
if(numRequests()>=maxLimit) {
throw OverLimit();
}
else {
requests.push_back(request);
}
return *this;
}
};
现在,问题如下:
让
s1
、s2
和s3
是LimitedNamedServer
类中的三个对象。 为什么下面的代码不能编译,这个问题怎么解决:
s1=s2+s3
我不知道为什么这不应该编译。 据我所知,我为类Server
定义的+
运算符也可以用于类LimitedNamedServer
对象。 我最好的猜测是,它发生的原因是在+
的实现中,我创建了一个新的 Server 而不是LimitedNamedServer
,并且发生错误是因为s1
期望接收LimitedNamedServer
对象,而这不是返回的对象。
然而,这只是一个猜测,有人可以解释一下原因吗?
试着向自己解释为什么它应该编译......
鉴于operator +
与Server
工作,问问自己如果允许编译该代码, name
和maxLimit
会发生什么。
提示: 什么是对象切片?
因此,如您所知,您还需要为LimitedNamedServer
定义一个operator +
。 典型的实现是:
template <class T>
LimitedNamedServer<T> operator+(const LimitedNamedServer<T> &lhs, const LimitedNamedServer<T> &rhs)
{
LimitedNamedServer result = lhs;
result += rhs;
return result;
}
以这种方式编写,您可以重用现有代码,而无需提供友谊。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.