如何在 C++ 中创建结构的实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19035461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:26:54  来源:igfitidea点击:

How to create an instance of a struct in C++?

c++struct

提问by G21

The issue is an "Access violation writing location 0x00000000"error message right after I initialize the bkvariable to NULL. My guess is I should reserve memory space in advance to assign NULL( something like Book bk = new Book();) but I have not been able to figure out how to do it in C++ till now.

这个问题是一个“访问冲突写入位置00000000”错误信息的权利后,我初始化bk变量NULL。我的猜测是我应该提前保留内存空间来分配NULL(类似于Book bk = new Book();),但直到现在我还无法弄清楚如何在 C++ 中做到这一点。

Book.h

书.h

#ifndef Book_H
#define Book_H

struct _book;
typedef _book* Book;

Book CreateBook(unsigned int pageNum);

Book.cpp

书.cpp

#include "Book.h"
#include <iostream>

#ifndef Book_CPP
#define Book_CPP

using namespace std;

struct _book
{
    int pageNum;
};

Book CreateBook( unsigned int pageNum){

    Book bk = NULL; 

    bk->pageNum = pageNum;

    return bk;
};

回答by bstamour

You're assigning bk to NULL and then trying to access a member of it. That's the same as a null pointer in Java, and what you're doing would typically raise a NullPointerException (thanks from the comments). If you want to create a pointer to your struct, you need to use operator new:

您将 bk 分配给 NULL,然后尝试访问它的成员。这与 Java 中的空指针相同,您所做的通常会引发 NullPointerException(感谢评论)。如果要创建指向结构的指针,则需要使用运算符 new:

bk = new _book;
// ...
return bk;

and then make sure you call delete on the pointer when you're done with it.

然后确保在完成后在指针上调用 delete 。

I would advise against using pointers here, though. Unlike other languages, C++ lets you create objects by value. It also allows for references and pointers, but only use pointers when you absolutely must. If you simply want to create a book object with a given pageNum, you should create a constructor while you're at it:

不过,我建议不要在这里使用指针。与其他语言不同,C++ 允许您按值创建对象。它还允许引用和指针,但仅在绝对必要时才使用指针。如果你只是想用给定的 pageNum 创建一个 book 对象,你应该在创建时创建一个构造函数:

struct _book {
    int pageNum;
    _book(int n) : pageNum(n) // Create an object of type _book.
    {
    }
};

and then you can invoke it like

然后你可以像这样调用它

_book myBook(5); // myBook.pageNum == 5

If you're new to C++, please get yourself a good book on it. It's not just a low-level language, and it's also not just an OOP language. It's a multi-paradigm swiss army knife language.

如果你是 C++ 的新手,请给自己找一本关于它的好书。它不仅仅是一种低级语言,也不仅仅是一种面向对象的语言。这是一种多范式的瑞士军刀语言。

回答by qxixp

This is what you need:

这是你需要的:

Book CreateBook( unsigned int pageNum){

    Book bk = new _book();

    bk->pageNum = pageNum;

    return bk;
}

your bk was null and you cannot access pageNum when the pointer is null.

您的 bk 为空,并且当指针为空时您无法访问 pageNum。

And don't forget to call delete on bk when you are done using it.

并且不要忘记在使用完 bk 后调用 delete 。

回答by Yakk - Adam Nevraumont

Book.h

书.h

#ifndef Book_H
#define Book_H

// why not put the layout here?    
struct Book
{
    int pageNum;
};
Book CreateBook(unsigned int pageNum);

#endif

Book.cpp

书.cpp

#include "Book.h"

// no #define guards
// do not using namespace std;, it is a bad habit

Book CreateBook( unsigned int pageNum){
  Book bk;
  bk.pageNum = pageNum;
  return bk;
};

This is the simplest solution. Books are actual values, and can be copied and moved around and the like.

这是最简单的解决方案。书籍是实际价值,可以复制和移动等。

If you needthe opacity of an abstract type, only then should you deal with pointers. When you do deal with pointers, hiding them behind a typedefis a bad idea: pointers mean resource management, so it should be obvious that you are using them.

如果您需要抽象类型的不透明度,那么您才应该处理指针。当您确实处理指针时,将它们隐藏在 a 后面typedef是一个坏主意:指针意味着资源管理,因此很明显您正在使用它们。

The pointer-based version:

基于指针的版本:

#ifndef Book_H
#define Book_H

// why not put the layout here?    
struct Book;
Book* CreateBook(unsigned int pageNum);

#endif

* Book.cpp *

* Book.cpp *

#include "Book.h"

// no #define guards
// do not using namespace std;, it is a bad habit

Book* CreateBook( unsigned int pageNum){
  Book* bk = new Book;
  bk->pageNum = pageNum;
  return bk;
};

but, if you are creating stuff, you should probably create smart pointers:

但是,如果您正在创建东西,您可能应该创建智能指针:

#include <memory>
std::shared_ptr<Book> CreateBook( unsigned int pageNum){
  std::shared_ptr<Book> bk( new Book );
  bk->pageNum = pageNum;
  return bk;
};

回答by Manjunath Bhadrannavar

but if you dont want to create a variable from heap then, you can directly create and return this way

但是如果您不想从堆创建变量,则可以直接以这种方式创建和返回

bk = _book{any_data_that_you_want_to_insert};
// ...
return bk;

回答by iseletsky

Why are you doing the typedefing? It can be good practice in some cases for some reason I guess.

你为什么要打字?出于某种原因,我猜在某些情况下这可能是一种很好的做法。

In case you didn't know, you could also write just:

如果你不知道,你也可以只写:

_book book;

_书本;

Now book is allocated statically on the stack instead of dynamically in the heap. It'll get destroyed automatically when the variable goes out of scope just like int or double, etc...

现在 book 在堆栈上静态分配,而不是在堆中动态分配。当变量超出范围时,它会自动销毁,就像 int 或 double 等......

This is useful sometimes if you want to avoid the overhead or work of allocating memory for something really simple. It was weird for me to go into Java and have to say,

如果您想避免为一些非常简单的事情分配内存的开销或工作,这有时很有用。进入 Java 对我来说很奇怪,不得不说,

vec3 position = new Vec3(0.0, 1.0, 5.0);

vec3 位置 = 新的 Vec3(0.0, 1.0, 5.0);

instead of just saying

而不是只是说

vec3 position(0.0, 1.0, 5.0);

vec3 位置(0.0, 1.0, 5.0);

like you would in C++.

就像在 C++ 中一样。

回答by SigTerm

struct Book{
    int pageNum;    
};

Book* createBook(int pageNum){
    Book *result = new Book;
    result->pageNum = pageNum;
    return result;
}

int main(int argc, char** argv){
    Book book;
    book.pageNum = 0;
    return 0;
}

or

或者

struct Book{
    int pageNum;    
    Book(int pageNum_ = 0)
    :pageNum(pageNum_){
    }
};

Book* createBook(int pageNum){
    return new Book(pageNum);
}

int main(int argc, char** argv){
    Book book(0);
    return 0;
}

回答by P0W

In

Book bk;

Book bk;

bkis a pointer

bk是一个指针

Allocate memory for it first

先为它分配内存

Book bk* = new _book();

Book bk* = new _book();

And then do

然后做

bk->pageNum = pageNum;

bk->pageNum = pageNum;

Also don't forget to free the memory using

也不要忘记使用释放内存

delete bk;

delete bk;

回答by Simple

There are a few mistakes in your code.

您的代码中有一些错误。

  1. You need to put an #endifat the end of your header file.
  2. You need to place a semicolon at the end of struct, classand uniondefinitions (after the closing brace).
  3. You shouldn't be using pointers at all in such a simple use case.
  1. 您需要#endif在头文件的末尾放置一个。
  2. 您需要在struct,classunion定义的末尾放置一个分号(在右大括号之后)。
  3. 在这样一个简单的用例中,您根本不应该使用指针。

Example:

例子:

Book.h

书.h

#ifndef BOOK_H
#define BOOK_H

struct Book
{
    int pageNum;
};

Book CreateBook(int pageNum);

#endif


Book.cpp

书.cpp

#include "Book.h"

Book CreateBook(int pageNum)
{
    Book bk;

    bk.pageNum = pageNum;

    return bk;
}

You don't need the CreateBookfunction anyway but I left it in anyway.

CreateBook反正你不需要这个功能,但我还是把它留在了。