C++:无法用new实例化我的类

C++: Cannot instantiate my class with new

本文关键字:实例化 我的 new C++      更新时间:2023-10-16

使用Eclipse CDT,我编写了一个抽象类"Lexer",它驻留在一个共享库项目中。它由"UTF8Lexer"在另一个共享库项目中继承。为此,我创建了一个UnitTest++测试项目,其中包含以下代码:

#include "UnitTest++.h"
#include "UTF8Lexer.h"
#include <fstream>
using namespace std;
programma::Lexer<UChar32, icu::UnicodeString>* getLexer(string sampleFile)
{
    string path = "../samples/" + sampleFile;
    ifstream* stream = new ifstream();
    stream->open (path.data());
    programma::UTF8Lexer l1(stream); //This line compiles fine.
    programma::UTF8Lexer* l2 = new  programma::UTF8Lexer(stream); // Error: "Type 'programma::UTF8Lexer' could not be resolved"
    return l2;
}

我不明白为什么他喜欢l1的声明,但不喜欢l2的声明…这个典型的不具体的错误消息并没有给我太多线索(虽然我是C++的新手,但我在大学的计算机科学课程中用C#做了很多工作…(。我认为它不能是任何遗漏的参考或包含,因为它实际上处理l1声明。。。但是,如果我在同一个源文件中创建其他类,并以相同的方式实例化它,一切都会正常。。。

我使用本教程将库连接到它们的使用项目,所以这应该很好。

我也在谷歌上搜索了很多,但事实证明,要么无法找到这个问题的特定搜索词,要么我发现了某种特殊情况。。。

以下是上述课程的节选:

  • UTF8Lexer.h:

    #ifndef UTF8LEXER_H_
    #define UTF8LEXER_H_
    
    #include "unicode/unistr.h"
    #include "Lexer.h"
    #include <iostream>
    using namespace icu;
    namespace programma {
    class UTF8Lexer : public Lexer<UChar32, UnicodeString> {
    public:
        UTF8Lexer(std::istream* source);
        ~UTF8Lexer();
    ...
    
  • UTF8Lexer.cpp:

    #include "UTF8Lexer.h"
    namespace programma {
    programma::UTF8Lexer::UTF8Lexer(std::istream* source)
    {
    }
    programma::UTF8Lexer::~UTF8Lexer() {
    }
    ...
    
  • Lexer.h:

    #ifndef LEXER_H_
    #define LEXER_H_
    #include "Token.h"
    namespace programma {
    template<typename C, typename S> class Lexer {
    public:
    ...
    

programma::UTF8Lexer l1(stream);可能被解析为programma::UTF8Lexer l1(std::stream __Unnamed_Argument);,即一个名为l1的函数的声明。删除using namespace std::以解决此问题。

我发现了造成我麻烦的原因:正确地将"UTF8Lexer"命名为"UTFLxer"解决了所有问题。但是,几个小时后,我和一个班上的成员也遇到了同样的问题。在处理完这个看起来完全不起作用的Eclipse/CDT/GCC设置几分钟后,我想到了为项目重建索引的想法:只需右键单击项目,选择"索引"->"重建"。现在它起作用了。