【问题标题】:Why will the following code not compile (inheritance in c++)为什么下面的代码不能编译(c++中的继承)
【发布时间】:2019-07-20 18:16:16
【问题描述】:

所以这不是我遇到的问题,而是考试中我无法正确回答的问题。

我有以下课程:

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 的类,这些类之间的区别在于LimitedNamedServerobjects 具有最大请求容量和名称。

这就是它的样子:

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;
}
};

现在,问题如下:

s1s2s3 成为LimitedNamedServer 类中的三个对象。为什么下面的代码会编译不出来,这个问题怎么解决:

s1=s2+s3

我不知道为什么不应该编译。据我所知,我为Server 类定义的+ 运算符也可用于LimitedNamedServer 类中的对象。我最好的猜测是它发生在+ 的实现内部,我创建了一个新服务器而不是LimitedNamedServer,并且发生错误是因为s1 期望收到LimitedNamedServer 对象,而这是不是返回的对象。

这只是猜测,有人可以解释一下原因吗?

【问题讨论】:

  • 究竟是什么错误?请格式化您的代码。
  • 一件事是LimitedNamedServer 缺少class 关键字,但实际上,最简单的方法是实际编译它并检查真正的错误。
  • 您能否正确缩进您的代码以便我们阅读?
  • 只需编译它,您就会立即看到问题所在。不过,您需要先真正完成程序,因为这里缺少大量代码。
  • @איתן לוי 然后第一步是运行它以产生错误。试图猜测不是很好地利用时间。

标签: c++ inheritance


【解决方案1】:

尝试向自己解释为什么它应该编译...

鉴于operator +Server 一起使用,问问自己如果允许编译该代码,namemaxLimit 会发生什么。

提示:What is object slicing?

如您所知,您还需要为LimitedNamedServer 定义一个operator +。典型的实现是:

template <class T>
LimitedNamedServer<T> operator+(const LimitedNamedServer<T> &lhs, const LimitedNamedServer<T> &rhs)
{
    LimitedNamedServer result = lhs;
    result += rhs;
    return result;
}

这样写,你可以重复使用现有的代码,不需要交友。

【讨论】:

  • 这可以通过使第一个参数按值而不是 const-reference 并完全删除 result 来进一步增强。然后生成的代码就变成了lhs += rhs; return lhs;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
  • 2015-06-12
  • 2014-05-12
  • 2010-10-24
  • 1970-01-01
  • 2012-05-28
相关资源
最近更新 更多