I know that the code below works.
int* pn;
pn = new int;
So I tried to apply it in same way, in my custom class.
class Matrix {
private:
typedef struct ex_node* ex_pointer;
typedef struct ex_node {
int ex_data;
ex_pointer next;
};
public:
void examplefunction() {
ex_pointer node;
node = new ex_node; //error here
}
};
The error says that I cannot assign "ex_node*" type value to "ex_pointer"type entity.
But ex_pointer is defined as ex_node*.
Is ex_pointer different type from ex_node*? How can I remove this error?
CodePudding user response:
A more C way(and correct way) of doing this would be remove the unnecessary typedef
s as shown below:
class Matrix {
private:
struct ex_node {
int ex_data;
//------vvvvvvvv---------->directly using ex_node* is more clear IMO
ex_node* next;
};
using ex_pointer = ex_node*;
public:
void examplefunction(){
//------vvvvvvvvvv---------->you can use ex_pointer if you really want
ex_pointer node;
node = new ex_node;; //works now
}
};
Method 2
If you want you can still use alias as shown below. Here we provide a forward declaration for ex_node
inside the Matrix
so that we can use typedef/using with it.
class Matrix {
private:
struct ex_node; //forward declaration
using ex_pointer = ex_node*;
struct ex_node {
int ex_data;
//------vvvvvvvvv---------->use ex_pointer
ex_pointer next;
};
public:
void examplefunction(){
ex_pointer node;
node = new ex_node;;
}
};
CodePudding user response:
I like the question and Jason Liam already provided different ways to fix your code. But I'd like to answer your first questions, which are entirely valid: "The error says that I cannot assign "ex_node" type value to "ex_pointer"type entity. But ex_pointer is defined as ex_node*. Is ex_pointer different type from ex_node*?"
Let's check exactly what the compiler says:
error: incompatible pointer types assigning to 'Matrix::ex_pointer' (aka 'ex_node *')
from 'Matrix::ex_node *'
node = new ex_node;
^~~~~~~~~~~
So, the problem is that node is of type Matrix::ex_pointer
, that is a ex_node *
. new ex_node
instead is of type Matrix::ex_node *
. The former is a pointer to a struct ex_node
defined in the global namespace, while the latter is a pointer to a struct ex_node
defined within class Matrix
.
Apparently forward declaring a struct within a typedef assumes that the struct is in the global namespace, which in your case is not correct. You can fix it (as suggested also by Jason Liam) by forward declaring your struct before the typedef:
class Matrix {
struct ex_node;
typedef struct ex_node* ex_pointer;
struct ex_node {
int ex_data;
ex_pointer next;
};
public:
void examplefunction() {
ex_pointer node;
node = new ex_node;
}
};
Finally: don't hide that pointer behind a typedef.