简体   繁体   中英

Including a class to define a global variable parameter c++ :(

I'm trying to implement a SmartPtr class in my code that used to use normal pointers. I've looked at other sof questions and their solutions seem to be what I'm doing, so I'm not sure what's wrong. I had to define my global in graph.h because a function parameter, shown, uses it.

./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.

I define it in 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); ...

This is 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

What is wrong ??? Edit: look at the follow up in the little box below.

You can have only declarations at global scope:

Adjacency null_adj;
null_adj.id = -1;

The first of these two lines is a declaration, the second is not. The way to avoid the need to have expressions at global scope is to encapsulate the operation into a function, eg, a constructor. That would also allow the use of the object initialization without the need of a separate object. With you current class you can use structured initialization:

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

The next step is then to avoid global variables entirely: they generally cause problems: I'd recommend against global variables and if they are consider essentially I'd recommend to make the constexpre or, at least, const . Note that const objects at global scope already suffer from an indeterministic initialization order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM