C++中对象实例化的语法是什么

What is the syntax for object instantiation in C++?

本文关键字:语法 是什么 实例化 对象 C++      更新时间:2023-10-16

当我编译以下c++代码时:

#include "ConstantList.h"
using namespace std;
int main() {
ConstantList* cl = new ConstantList();
//do something with cl
delete cl;
cl = NULL;
return 0;
}

编译器给了我错误:

Undefined symbols:
  "ConstantList::~ConstantList()", referenced from:
      _main in ccNfeeDU.o
  "ConstantList::ConstantList()", referenced from:
      _main in ccNfeeDU.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

我是否没有掌握实例化对象的正确语法?我的ConstantList.h文件如下:

#ifndef ConstantList_h
#define ConstantList_h
#include <string>
#include "Token.h"

using namespace std;
class ConstantListTail;
class ConstantList {
public:
    ConstantList();
    ~ConstantList();
    std::string toString();
    void push_back(Token*);
    void push_back(ConstantListTail*);
private:
    Token* termString;
    ConstantListTail* constantListTail;
};

#endif

非常感谢您的帮助!

您的语法是正确的,因为您得到的是链接器错误,而不是编译器错误。此错误意味着您在没有ConstantList.cpp源的情况下编译main,或在没有引用ConstantList.o 的情况下链接

使用此命令编译应修复错误:

g++ collect2.cpp ConstantList.cpp

(我假设具有main函数的文件名为collect2.cpp)。

"未定义的符号"表示您已经声明了标识符(在本例中为析构函数),并使用了它,但据链接器所知,您尚未将其定义为

在某个地方添加一个定义,并确保编译的版本在链接器链接的文件中


关于"实例化语法",不幸的是,在C++中没有专门的语法

相反,函数强制转换表示法用于构造函数调用

也许最接近纯实例化语法的是new表达式


重新

using namespace std;

在头文件中:不要

例如,标准库定义了distance。包含标头的某些代码有自己的distance并发生名称冲突的可能性有多大?远高于零。

这并不意味着头文件中永远不应该有using namespace std;,但头文件中的全局命名空间中永远不应有它。对于其他名称空间,要非常清楚它的作用,即提供所有标准库名称作为该名称空间的一部分。