【问题标题】:Why is stringstream member in class causing a Compile-time error? [duplicate]为什么类中的 stringstream 成员会导致编译时错误? [复制]
【发布时间】:2019-02-19 16:37:47
【问题描述】:

每当我尝试使用以下类运行我的程序时,都会收到与 std::stringstream newPredicate 声明相关的错误;一旦我删除该声明(以及在源代码中对其的任何使用),错误就会消失。

#ifndef LAB1_PREDICATE_H
#define LAB1_PREDICATE_H
#include <sstream>



class Predicate {
private:
public:
    std::stringstream newPredicate;
    void addToString(std::string tokenValue);
    void clearString();
   std::string toString();
};


#endif //LAB1_PREDICATE_H

以下是标头的源代码。我将 stringstream 设置为类成员,因此我可以通过任何函数访问它。

#include "Predicate.h"

void Predicate::addToString(std::string tokenValue) {
    newPredicate << tokenValue;
}

void Predicate::clearString() {
    newPredicate.clear();
}

std::string Predicate::toString() {
    std::string predicateString;
    newPredicate >> predicateString;
    return predicateString;
}

我在另一个类中多次调用 Predicate 对象。在我用想要的字符串值填充它之后,我将它推入一个向量并清除它。

std::vector<Predicate> myVector;
Predicate myPredicate;
myPredicate.addToString(myString); //I call this function a few times
myVector.push_back(myPredicate);
myPredicate.clearString();

这是错误信息

error: use of deleted function 'Predicate::Predicate(const Predicate&)'
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

然后是注释

note: 'Predicate::Predicate(const Predicate&)' is implicitly deleted because 
the default definition would be ill-formed:
class Predicate {
      ^~~~~~~~~

【问题讨论】:

  • 你是如何实例化和使用Predicate的?
  • 仅供参考,这是一个编译时错误,而不是运行时错误
  • 这不是运行时错误,您显示的代码也不会导致此编译器错误。至少不是自己。无论如何,问题只是您无法复制流。
  • 我敢打赌有更多的注释,也许有人会提到这一点,但问题是std::stringstream 无法复制,因此编译器无法生成有效的复制构造函数。

标签: c++


【解决方案1】:

std::stringstream 不可复制,因此未定义 Predicate 类的默认复制构造函数。

大概在您的代码中的某个地方,您正试图复制一个Predicate 对象。您要么需要从 Predicate 中删除 std::stringstream,要么定义自己的复制构造函数,要么不复制 Predicate 对象。

【讨论】:

  • 如前所述,操作需要显示,该类是如何使用的。
猜你喜欢
  • 1970-01-01
  • 2012-08-14
  • 2014-01-19
  • 1970-01-01
  • 2018-04-08
  • 2023-03-03
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多