I have some code in C, that uses incomplete structs this way ( simplified example ):
something.h
struct something;
struct something *new_something();
int work_a(struct something *something);
int work_b(struct something *something, const char *str);
void free_something(struct something *something);
somecode.c
int some_function()
{
struct something *something;
int x;
something = new_something();
x = work_a(something);
free_something(something);
return x;
}
I was thinking, I'm basically doing C++ here, why not try write it in C++ .
The question is ( I'm new to C++ ), how do I achieve the same in C++ ? If I try to add declare a member function of an incomplete class, I get
error: incomplete type 'something' named in nested name specifier
from clang. By writing the complete class in the header, this would lose the whole point of data hiding, and changing private vars in the class would force every file including "something.h" to recompile, which I think is not needed here. I don't need the files using "something.h" to know the size of this struct / class, I'm usually fine with having just a pointer. I suspected it should look like this:
class Something;
Something::Something();
Something::~Something();
int Something::work_a(int x);
this way I could write the same thing I did in C, only shorter, and even cleaner. Any C++ coder out there wishing to enlighten this mortal C coder?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…