【问题标题】:Reading from a txt file in class constructor [closed]从类构造函数中的 txt 文件中读取 [关闭]
【发布时间】:2014-04-10 14:30:49
【问题描述】:

我想测试构造函数的功能,遇到了一个有趣的问题。编译该代码后,我得到引用 main() 的链接错误 LNK2019。在我的情况下,如何能够逐行读取和复制 one.txt 的内容?我指的是前 7.01 版的“Thinking in C++”一书,但由于使用 Visual Studio 我不能使用 main(int argc, char* argv[]) 版本..

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Text
{
    string text;
public:
    Text();
    Text(const string& name) 
    {
        ifstream infile;
        infile.open(name);
        if(!infile.good())
        {
            cout << "File is not open";
        }
        else
        {
            string line;
            while(getline(infile,line))
                text = text + line + '\n';
        }
    };
    string contetns()
    {
        return text;
    };
};

int main()
{
    Text o1;
    Text o2("one.txt");
    cout << "content: " << o1.contetns() << endl;
    cout << "content: " << o2.contetns() << endl;
    system("pause");
}

【问题讨论】:

  • 您的空构造函数未定义。要么自己定义,要么使用Text() = default,如果你使用的是c++11。你已经声明Text::Text(); 没有提供定义,至少我在发布的代码中看不到它......
  • 我不认为错误消息说有一个未定义的引用 main,而是有一个未定义的引用inmain。以后在发布有关编译器或链接器错误的问题时,请在问题中包含 completeunedited 错误日志。
  • error LNK2019: 无法解析的外部符号“public: __thiscall Text::Text(void)”
  • 哦,谢谢,我太笨了!我需要找到正确解释错误消息的方法,以便追查原因..
  • @beginh 您可以将 int main(int argc...etc) 与 Visual Studio 一起使用。见这里stackoverflow.com/questions/3697299/…

标签: c++ ifstream


【解决方案1】:

你必须定义你的空析构函数。

【讨论】:

    【解决方案2】:

    正如 tmaric 所说,您需要一个空的构造函数:

    //Text();
    Text(){};
    

    【讨论】:

    • 这不是'Nam。有规则。 ;))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多