[英]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.