要声明一个类对象,我们需要这种格式
classname objectname;
Run Code Online (Sandbox Code Playgroud)
声明结构对象是否相同?
喜欢
structname objectname;
Run Code Online (Sandbox Code Playgroud)
struct Books Book1;
Run Code Online (Sandbox Code Playgroud)
其中Books是结构名称,Book1是其对象名称.那么struct在声明结构对象之前是否需要使用关键字?
您必须对它们进行typedef以创建没有struct关键字的对象
例子:
typedef struct Books {
char Title[40];
char Auth[50];
char Subj[100];
int Book_Id;
} Book;
Run Code Online (Sandbox Code Playgroud)
然后你可以定义一个没有struct关键字的对象,如:
Book thisBook;
Run Code Online (Sandbox Code Playgroud)
这是C和C++之间的差异之一.
在C++中,定义类时,可以使用带或不带关键字class(或struct)的类型名称.
// Define a class.
class A { int x; };
// Define a class (yes, a class, in C++ a struct is a kind of class).
struct B { int x; };
// You can use class / struct.
class A a;
struct B b;
// You can leave that out, too.
A a2;
B b2;
// You can define a function with the same name.
void A() { puts("Hello, world."); }
// And still define an object.
class A a3;
Run Code Online (Sandbox Code Playgroud)
在C中,情况有所不同.类不存在,相反,有结构.但是,您可以使用typedef.
// Define a structure.
struct A { int x; };
// Okay.
struct A a;
// Error!
A a2;
// Make a typedef...
typedef struct A A;
// OK, a typedef exists.
A a3;
Run Code Online (Sandbox Code Playgroud)
遇到与函数或变量具有相同名称的结构并不罕见.例如,stat()POSIX中的函数将a struct stat *作为参数.
是的。在C语言的情况下,您需要明确给出变量的类型,否则编译器将抛出错误:'Books' undeclared .(在上述情况下)
因此,如果您使用C语言,则需要使用关键字struct ,但如果您使用C++编写它,则可以跳过此步骤。
希望这可以帮助。