【发布时间】:2019-12-28 06:02:55
【问题描述】:
我正在尝试在我的代码中实现一个 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
怎么了??? 编辑:查看下面小框中的后续内容。
【问题讨论】:
-
您确实需要包含一个带有实际错误的minimal reproducible example,但是您尝试在不是指针的
Adjacency对象上使用箭头运算符:null_adj->id.那应该是nujll->id吗? -
您不能将
null_adj.id = -1;之类的代码放在全局命名空间中(即在函数或main之外)。如果你想给id成员一个 default 值,那么把它写到Adjacency的声明中…'int id = -1;`。 -
不要在你
#include其他地方的文件中使用using namespace。您必须更改智能指针以遵循三规则(甚至更好的五规则),在当前形式下,实现可能导致双重删除并在删除错误后使用。 -
t.niese 观点的解释:What is The Rule of Three? 我建议重命名 SmartPtr.cpp 而不是尝试链接它的原因文件:Why can templates only be implemented in the header file?
-
我强烈建议您解决在用例中使用
std::unique_ptr和std::shared_ptr时遇到的问题,而不是实现自己的智能指针。甚至 std 库在第一次尝试时也没有得到他们的智能指针实现 "right"(他们的第一次尝试是现在已弃用的std::auto_ptr),所以你不应该期望它是一个简单的让他们正确的任务。
标签: c++ class oop graph include