C++中对象实例化的语法是什么
What is the syntax for object instantiation in C++?
当我编译以下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;
,但头文件中的全局命名空间中永远不应有它。对于其他名称空间,要非常清楚它的作用,即提供所有标准库名称作为该名称空间的一部分。
相关文章:
- C++避免重复声明的语法是什么
- 使用基类指针调用基类的值构造函数的语法是什么?
- 这行/语法是什么意思?
- 初始化对象以在 C++08 中作为参数传递的首选语法是什么?
- 将引用绑定到指针的语法是什么?(各种)
- 这个typedef和转换运算符语法是什么意思
- 此语法是什么意思.(::*).
- 将显式指定的函数模板重载作为模板参数传递的正确语法是什么?
- 使用 pybind11 绑定 typedef 类型的正确语法是什么?
- 将此类传递给引用的正确语法是什么?
- 带有约束的可变参数模板的'requires'表达式的语法是什么?
- 在TensorFlow C++中用于feed_dict的语法是什么?
- 调用模板化类内的枚举类枚举器的正确语法是什么
- 返回没有 typedef 的成员函数指针的语法是什么?
- 将强制转换运算符重载到 std::map 的正确语法是什么
- 这种增量语法是什么意思
- 返回结构的方法的正确语法是什么
- C 中的(*)语法是什么意思
- 堆栈(int = 10),这个语法是什么意思(C++)
- variadic模板阵列参考参数的语法是什么?