【问题标题】:Use of deleted function error occurs when the constructor of a class calls its member function?类的构造函数调用其成员函数时出现使用删除函数错误?
【发布时间】:2015-10-24 15:18:04
【问题描述】:

我有一些工作要构造函数去做,所以我在构造函数内部调用了一个成员函数:

    #include<iostream>
    #include<fstream>
    #include<string>
    using namespace std;

    class Token{
    public:
        Token() {}
        Token(const string &targetfile);
        void GetToken();
        ifstream in;
    };
    Token::Token(const string &targetfile)
    {
        in.open(targetfile);    
        GetToken();
    }
    void Token::GetToken()
    {
        in.close();
    }
    int main(int argc,char *argv[])
    {
        Token first = Token(string(argv[1]));
        return 0;
    }

我收到这样的错误:

使用已删除函数‘Token::Token(Token&&)’ 注意:'Token::Token(Token&&)' 被隐式删除,因为默认定义格式不正确

【问题讨论】:

  • 使用 g++ 编译:ideone.com/M4BAgN
  • 我得到错误使用:g++ -std=c++11 debug.cpp -o debug
  • 您尝试过不同的选择吗? ideone.com 使用 C++14
  • 我发现如果我删除了与ifstream相关的代码然后它会编译。但我不知道文件流有什么问题。
  • std::fstream 和其他流类无法复制或分配。因此,编译器无法为包含此类流的其他对象生成默认赋值运算符或复制构造函数。您要么定义自己的类型,要么无法复制或分配您的类型。顺便说一句:你本可以自己回答你的问题。应该很容易找出对成员函数的调用是否会产生影响。

标签: c++


【解决方案1】:

使用Token first(string(argv[1])); 而不是Token first = Token(string(argv[1]));

这样就不会调用额外的移动操作符了。

【讨论】:

  • string 构造函数是隐式的,请改用Token first(argv[1]);
  • @Dragos 这是一个函数声明。
  • @0x499602D2 它可以在另一个上下文中,但在这个上下文中,它是一个带有显式构造函数的变量声明。
  • @Ulrich Eckhardt 你是对的。感谢您的观察。
猜你喜欢
  • 2011-12-07
  • 2011-03-06
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 2017-09-07
相关资源
最近更新 更多