[英]Including a class to define a global variable parameter c++ :(
我试图在我的代码中实现一个用于使用普通指针的 SmartPtr 类。 我查看了其他问题,他们的解决方案似乎就是我正在做的,所以我不确定出了什么问题。 我必须在 graph.h 中定义我的全局变量,因为显示的函数参数使用它。
./graph.h:14:1: error: unknown type name 'null_adj'
null_adj.id = -1;
^
./graph.h:14:9: error: cannot use dot operator on a type
null_adj.id = -1;
^
2 errors generated.
我在graph.h中定义它:
#include "node.h"
#include "SmartPtr.cpp"
using namespace std;
Adjacency null_adj;
null_adj.id = -1;
SmartPtr<Adjacency> null(&null_adj);
class Graph { ...
void insert_and_delete(stuff, SmartPtr<Adjacency> second_insert = null); ...
这是 node.h:
#include "SmartPtr.cpp"
#include <vector>
using namespace std;
struct Adjacency{
public:
int id;
char letter;
int type;
};
class Node { ...
SmartPtr.cpp:
#ifndef SMARTPTR_CPP
#define SMARTPTR_CPP
#include<iostream>
using namespace std;
// A generic smart pointer class
template <class T>
class SmartPtr
{
T *ptr; // Actual pointer
public:
// Constructor
explicit SmartPtr(T *p = NULL) { ptr = p; }
// Destructor
~SmartPtr() { delete(ptr); }
// Overloading dereferncing operator
T & operator * () { return *ptr; }
// Overloding arrow operator so that members of T can be accessed
// like a pointer (useful if T represents a class or struct or
// union type)
T * operator -> () { return ptr; }
};
#endif
怎么了 ??? 编辑:查看下面小框中的后续内容。
您只能在全局范围内声明:
Adjacency null_adj;
null_adj.id = -1;
这两行中的第一行是声明,第二行不是。 避免需要在全局范围内使用表达式的方法是将操作封装到函数中,例如构造函数。 这也将允许在不需要单独对象的情况下使用对象初始化。 使用当前类,您可以使用结构化初始化:
SmartPtr<Adjacency> sp(new Adjacency{-1});
下一步是完全避免全局变量:它们通常会引起问题:我建议不要使用全局变量,如果它们基本上被考虑,我建议使用constexpre
或至少是const
。 请注意,全局范围内的const
对象已经受到不确定的初始化顺序的影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.