包括一个类来定义一个全局变量参数 c++ :(

Posted

技术标签:

【中文标题】包括一个类来定义一个全局变量参数 c++ :(【英文标题】:Including a class to define a global variable parameter c++ :( 【发布时间】: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-&gt;id .那应该是nujll-&gt;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_ptrstd::shared_ptr 时遇到的问题,而不是实现自己的智能指针。甚至 std 库在第一次尝试时也没有得到他们的智能指针实现 "right"(他们的第一次尝试是现在已弃用的std::auto_ptr),所以你不应该期望它是一个简单的让他们正确的任务。 【参考方案1】:

您只能在全局范围内声明:

Adjacency null_adj;
null_adj.id = -1;

这两行的第一行是声明,第二行不是。避免在全局范围内需要表达式的方法是将操作封装到一个函数中,例如构造函数。这也将允许使用对象初始化而不需要单独的对象。对于当前的课程,您可以使用结构化初始化:

SmartPtr<Adjacency> sp(new Adjacency-1);

下一步是完全避免使用全局变量:它们通常会导致问题:我建议不要使用全局变量,如果从本质上考虑它们,我建议使用 constexpre 或至少 const .请注意,全局范围内的 const 对象已经遭受了不确定的初始化顺序。

【讨论】:

谢谢!现在我得到“ld:symbol(s) not found for architecture x86_64”。我以前没有得到那个错误。尝试编写一个新的、简单的 makefile,但得到了同样的错误。怎么回事?

以上是关于包括一个类来定义一个全局变量参数 c++ :(的主要内容,如果未能解决你的问题,请参考以下文章

VS C++警惕项目中文件全局变量冲突!!!!!!!!

python 中怎么对一个全局的图变量在函数中进行值修改

C++报错:全局变量重定义或是多次定义

C++ 怎么定义一个全局函数,能够在一个工程的所有文件中使用!

有没有更好的方法来定义全局变量?

C++ - 21局部变量和全局变量的区别