在c++中,我不能理解指针和类。

时间:2021-03-19 21:42:13

I'm fresh out of college and have been working in C++ for some time now. I understand all the basics of C++ and use them, but I'm having a hard time grasping more advanced topics like pointers and classes. I've read some books and tutorials and I understand the examples in them, but then when I look at some advanced real life examples I cannot figure them out. This is killing me because I feel like its keeping me from bring my C++ programming to the next level. Did anybody else have this problem? If so, how did you break through it? Does anyone know of any books or tutorials that really describe pointers and class concepts well? or maybe some example code with good descriptive comments using advanced pointers and class techniques? any help would be greatly appreciated.

我刚从大学毕业,现在已经在c++工作了一段时间。我理解c++的所有基础知识并使用它们,但是我很难掌握更高级的主题,比如指针和类。我读过一些书和教程,我理解其中的一些例子,但当我看到一些高级的现实生活的例子时,我无法理解它们。这让我很痛苦,因为我觉得它让我无法将c++编程提升到更高的水平。还有人有这个问题吗?如果是这样,你是如何突破它的?有没有人知道什么书或教程真正描述了指针和类概念?或者是使用高级指针和类技术编写具有良好描述性注释的示例代码?非常感谢您的帮助。

27 个解决方案

#1


19  

Understanding Pointers in C/C++

在C / c++理解指针

Before one can understand how pointers work, it is necessary to understand how variables are stored and accessed in programs. Every variable has 2 parts to it - (1) the memory address where the data is stored and (2) the value of the data stored.

在理解指针如何工作之前,有必要了解如何在程序中存储和访问变量。每个变量都有两个部分—(1)存储数据的内存地址和(2)存储数据的值。

The memory address is often referred to as the lvalue of a variable, and the value of the data stored is referred to as the rvalue (l and r meaning left and right).

内存地址通常被称为变量的lvalue,存储的数据的值被称为rvalue (l和r分别表示左和右)。

Consider the statement:

考虑语句:

int x = 10;

Internally, the program associates a memory address with the variable x. In this case, let's assume that the program assigns x to reside at the address 1001 (not a realistic address, but chosen for simplicity). Therefore, the lvalue (memory address) of x is 1001, and the rvalue (data value) of x is 10.

在内部,程序将一个内存地址与变量x关联。在本例中,我们假设程序将x分配到地址1001(不是一个实际的地址,而是为了简单起见而选择的)。因此,x的lvalue(内存地址)为1001,x的rvalue(数据值)为10。

The rvalue is accessed by simply using the variable “x”. In order to access the lvalue, the “address of” operator (‘&’) is needed. The expression ‘&x’ is read as "the address of x".

只要使用变量“x”就可以访问rvalue。为了访问lvalue,需要操作符(' & ')的“地址”。表达式' &x '被读为" x的地址"。

Expression          Value
----------------------------------
x                   10
&x                  1001

The value stored in x can be changed at any time (e.g. x = 20), but the address of x (&x) can never be changed.

存储在x中的值可以随时更改(例如x = 20),但是x (&x)的地址永远不能更改。

A pointer is simply a variable that can be used to modify another variable. It does this by having a memory address for its rvalue. That is, it points to another location in memory.

指针只是一个可以用来修改另一个变量的变量。它通过为其rvalue设置一个内存地址来实现这一点。也就是说,它指向内存中的另一个位置。

Creating a pointer to “x” is done as follows:

创建指向“x”的指针如下所示:

int* xptr = &x;

The “int*” tells the compiler that we are creating a pointer to an integer value. The “= &x” part tells the compiler that we are assigning the address of x to the rvalue of xptr. Thus, we are telling the compiler that xptr “points to” x.

“int*”告诉编译器我们正在创建一个指向整数值的指针。“= &x”部分告诉编译器我们正在将x的地址赋给xptr的rvalue。因此,我们告诉编译器xptr指向“x”。

Assuming that xptr is assigned to a memory address of 1002, then the program’s memory might look like this:

假设xptr被分配到1002的内存地址,那么程序的内存可能是这样的:

Variable    lvalue    rvalue
--------------------------------------------
x           1001      10   
xptr        1002      1001

The next piece of the puzzle is the "indirection operator" (‘*’), which is used as follows:

下一个难题是“间接运算符”(' * '),它的用法如下:

int y = *xptr;

The indirection operator tells the program to interpret the rvalue of xptr as a memory address rather than a data value. That is, the program looks for the data value (10) stored at the address provided by xptr (1001).

间接运算符告诉程序将xptr的rvalue解释为一个内存地址,而不是一个数据值。即,程序查找存储在xptr(1001)提供的地址中的数据值(10)。

Putting it all together:

把它放在一起:

Expression      Value
--------------------------------------------
x                   10
&x                  1001
xptr                1001
&xptr               1002
*xptr               10

Now that the concepts have been explained, here is some code to demonstrate the power of pointers:

既然已经解释了这些概念,下面的代码演示了指针的威力:

int x = 10;
int *xptr = &x;

printf("x = %d\n", x);
printf("&x = %d\n", &x);        
printf("xptr = %d\n", xptr);
printf("*xptr = %d\n", *xptr);

*xptr = 20;

printf("x = %d\n", x);
printf("*xptr = %d\n", *xptr);

For output you would see (Note: the memory address will be different each time):

对于输出,您将看到(注意:内存地址每次都会不同):

x = 10
&x = 3537176
xptr = 3537176
*xptr = 10
x = 20
*xptr = 20

Notice how assigning a value to ‘*xptr’ changed the value of ‘x’. This is because ‘*xptr’ and ‘x’ refer to the same location in memory, as evidenced by ‘&x’ and ‘xptr’ having the same value.

注意,将值赋给' *xptr '会如何改变' x '的值。这是因为' *xptr '和' x '在内存中表示相同的位置,' &x '和' xptr '具有相同的值。

#2


18  

Pointers and classes aren't really advanced topics in C++. They are pretty fundamental.

在c++中,指针和类并不是真正的高级主题。他们是很基本的。

For me, pointers solidified when I started drawing boxes with arrows. Draw a box for an int. And int* is now a separate box with an arrow pointing to the int box.

对我来说,当我开始用箭头画盒子的时候,指针就凝固了。绘制一个int型的方框。int*现在是一个单独的方框,箭头指向int型方框。

So:

所以:

int foo = 3;           // integer
int* bar = &foo;       // assigns the address of foo to my pointer bar

With my pointer's box (bar) I have the choice of either looking at the address inside the box. (Which is the memory address of foo). Or I can manipulate whatever I have an address to. That manipulation means I'm following that arrow to the integer (foo).

使用我的指针的框(栏),我可以选择查看盒子里面的地址。(是foo的内存地址)或者我可以操纵我的地址。这个操作意味着我沿着箭头指向整型(foo)

*bar = 5;  // asterix means "dereference" (follow the arrow), foo is now 5
bar = 0;   // I just changed the address that bar points to

Classes are another topic entirely. There's some books on object oriented design, but I don't know good ones for beginners of the top of my head. You might have luck with an intro Java book.

课程完全是另一个主题。有一些关于面向对象设计的书,但是我不知道适合我的头顶初学者的书。你可能会有一本介绍Java的书。

#3


7  

This link has a video describing how pointers work, with claymation. Informative, and easy to digest.

这个链接有一个视频描述指针是如何工作的,用的是claymation。内容丰富,易于理解。

This page has some good information on the basic of classes.

这个页面有一些关于基本类的好信息。

#4


4  

I used to have a problem understand pointers in pascal way back :) Once i started doing assembler pointers was really the only way to access memory and it just hit me. It might sound like a far shot, but trying out assembler (which is always a good idea to try and understand what computers is really about) probably will teach you pointers. Classes - well i don't understand your problem - was your schooling pure structured programming? A class is just a logical way of looking at real life models - you're trying to solve a problem which could be summed up in a number of objects/classes.

我曾经遇到过这样的问题,理解pascal语言中的指针:)一旦我开始做汇编指针,它真的是访问内存的唯一方法,它就会击中我。这听起来可能有点遥不可及,但尝试汇编程序(尝试理解计算机的真正含义总是一个好主意)可能会教会您指针。课堂——我不明白你的问题——你的学校是纯粹的结构化编程吗?一个类仅仅是观察现实生活模型的一种逻辑方法——你正在尝试解决一个问题,这个问题可以在一些对象/类中进行总结。

#5


3  

Pointers and classes are completely different topics so I wouldn't really lump them in together like this. Of the two, I would say pointers are more fundamental.

指针和类是完全不同的主题,所以我不会像这样把它们放在一起。在这两者中,指针是最基本的。

A good exercise for learning about what pointers are is the following:

下面是一个很好的练习来学习什么是指针:

  1. create a linked list
  2. 创建一个链表
  3. iterate through it from start to finish
  4. 从头到尾遍历它。
  5. reverse it so that the head is now the back and the back is now the head
  6. 倒转它,使头部现在是背面,背面现在是头部

Do it all on a whiteboard first. If you can do this easily, you should have no more problems understanding what pointers are.

首先在白板上做这些。如果你能很容易地做到这一点,你就不会有任何问题去理解指针是什么了。

#6


2  

Pointers already seem to be addressed (no pun intended) in other answers.

指针似乎已经在其他答案中被提及(没有双关语意思)。

Classes are fundamental to OO. I had tremendous trouble wrenching my head into OO - like, ten years of failed attempts. The book that finally helped me was Craig Larman's "Applying UML and Patterns". I know it sounds as if it's about something different, but it really does a great job of easing you into the world of classes and objects.

类是OO的基础。我绞尽脑汁,绞尽脑汁,想了10年的失败尝试。最终帮助我的书是Craig Larman的《应用UML和模式》。我知道这听起来好像是关于一些不同的东西,但它确实很好地让你进入了类和对象的世界。

#7


2  

We were just discussing some of the aspects of C++ and OO at lunch, someone (a great engineer actually) was saying that unless you have a really strong programming background before you learn C++, it will literally ruin you.

我们刚刚在午餐时间讨论了c++和OO的一些方面,有人(实际上是一位伟大的工程师)说,除非你在学习c++之前有非常强的编程背景,否则它会毁了你。

I highly recommend learning another language first, then shifting to C++ when you need it. It's not like there is anything great about pointers, they are simply a vestigial piece left over from when it was difficult for a compiler convert operations to assembly efficiently without them.

我强烈建议先学习另一种语言,然后在需要的时候转向c++。这并不是说指针有什么了不起的地方,它们只是一个遗留的片段,当编译器很难在没有它们的情况下有效地将操作转换为程序集时,它们就会被遗留下来。

These days if a compiler can't optimize an array operation better then you can using pointers, your compiler is broken.

现在,如果编译器不能更好地优化数组操作,那么就可以使用指针,那么编译器就坏了。

Please don't get me wrong, I'm not saying C++ is horrible or anything and don't want to start an advocacy discussion, I've used it and use it occasionally now, I'm just recommending you start with something else.

请不要误解我的意思,我并不是说c++很可怕或者其他什么,我也不想开始一场倡导性的讨论,我已经用过它了,现在偶尔用一下,我只是建议你从别的东西开始。

It's really NOT like learning to drive a manual car then easily being able to apply that to an automatic, it's more like learning to drive on one of those huge construction cranes then assuming that will apply when you start to drive a car--then you find yourself driving your car down the middle of the street at 5mph with your emergency lights on.

真的很不喜欢学习开手动车那么容易能够应用到自动,它更像是学开车在一个巨大的建筑起重机假设将当你开始开车,那么你会发现自己开车的*大街在5英里每小时和你紧急照明设备。

[edit] reviewing that last paragraph--I think that may have been my most accurate analogy ever!

[编辑]回顾最后一段——我认为这可能是我做过的最准确的类比!

#8


1  

To understand pointers, I can't recommend the K&R book highly enough.

要理解指针,我无法向您推荐K&R这本书。

#9


1  

For Pointers:

指针:

I found this post had very thoughtful discussion about pointers. Maybe that would help. Are you familar with refrences such as in C#? That is something that actually refers to something else? Thats probably a good start for understanding pointers.

我发现这篇文章对指针进行了非常深入的讨论。也许会有所帮助。你熟悉c#之类的折射率吗?这实际上是指其他的东西?这可能是理解指针的良好开端。

Also, look at Kent Fredric's post below on another way to introduce yourself to pointers.

另外,看看下面Kent Fredric的文章,介绍一下指针。

#10


1  

Learn assembly language and then learn C. Then you will know what the underlying principles of machine are (and thefore pointers).

学习汇编语言,然后学习c语言,这样你就会知道机器的基本原理是什么(以及前面的指针)。

Pointers and classes are fundamental aspects of C++. If you don't understand them then it means that you don't really understand C++.

指针和类是c++的基本方面。如果你不理解它们,那就意味着你不理解c++。

Personally I held back on C++ for several years until I felt I had a firm grasp of C and what was happening under the hood in assembly language. Although this was quite a long time ago now I think it really benefited my career to understand how the computer works at a low-level.

就我个人而言,几年来我一直对c++持保留态度,直到我觉得自己对C有了牢固的掌握,以及汇编语言背后发生的事情。虽然这是很久以前的事了,但现在我认为我的职业生涯确实受益于计算机在低水平的工作。

Learning to program can take many years, but you should stick with it because it is a very rewarding career.

学习编程可能需要很多年的时间,但你应该坚持下去,因为这是一个非常有益的职业。

#11


1  

There's no substiture for practicing.

没有进行练习的技巧。

It's easy to read through a book or listen to a lecture and feel like you're following what's going on.

读一本书或听一场讲座很容易,你会觉得自己在听。

What I would recommend is taking some of the code examples (I assume you have them on disk somewhere), compile them and run them, then try to change them to do something different.

我建议您使用一些代码示例(我假设您在磁盘上有它们),编译并运行它们,然后尝试更改它们以执行一些不同的操作。

  • Add another subclass to a hierarchy
  • 向层次结构添加另一个子类
  • Add a method to an existing class
  • 向现有类添加方法
  • Change an algorithm that iterates forward through a collection to go backward instead.
  • 更改在集合中向前迭代的算法,改为向后迭代。

I don't think there's any "silver bullet" book that's going to do it.

我不认为有什么“银弹”的书能做到这一点。

For me, what drove home what pointers meant was working in assembly, and seeing that a pointer was actually just an address, and that having a pointer didn't mean that what it pointed to was a meaningful object.

对我来说,指针的意义在于在汇编中工作,看到指针实际上只是一个地址,而拥有指针并不意味着它指向的是一个有意义的对象。

#12


1  

In the case of classes I had three techniques that really helped me make the jump into real object oriented programming.

在类的例子中,我有三种技术可以帮助我进入真正的面向对象编程。

The first was I worked on a game project that made heavy use of classes and objects, with heavy use of generalization (kind-of or is-a relationship, ex. student is a kind of person) and composition (has-a relationship, ex. student has a student loan). Breaking apart this code took a lot of work, but really brought things into perspective.

第一个是我在一个游戏项目中大量使用类和对象,大量使用泛化(类的或is的)关系,例如,学生是一种人)和构成(类的关系,例如,学生有学生贷款)。分解这段代码需要花费大量的工作,但真正让事情变得有意义。

The second thing that helped was in my System Analysis class, where I had to make http://www.agilemodeling.com/artifacts/classDiagram.htm">UML class diagrams. These I just really found helped me understand the structure of classes in a program.

第二件有帮助的事情是在我的系统分析类中,我必须创建http://www.agilemodeling.com/artifacts/classDiagram.htm“>UML类图。我刚刚发现的这些帮助我理解了程序中类的结构。

Lastly, I help tutor students at my college in programming. All I can really say about this is you learn a lot by teaching and by seeing other people's approach to a problem. Many times a student will try things that I would never have thought of, but usually make a lot of sense and they just have problems implementing their idea.

最后,我在我的大学里帮助指导学生们编程。我能说的是,通过教学和观察别人解决问题的方法,你能学到很多东西。很多时候,学生都会尝试一些我从未想过的事情,但通常都是很有意义的,他们只是在实现自己的想法时遇到了问题。

My best word of advice is it takes a lot of practice, and the more you program the better you will understand it.

我最好的建议是,这需要大量的练习,编程越多,你就越能理解它。

#13


0  

The best book I've read on these topics is Thinking in C++ by Bruce Eckel. You can download it for free here.

关于这些话题,我读过的最好的书是布鲁斯·埃克尔(Bruce Eckel)的《用c++思考》(Thinking in c++)。你可以在这里免费下载。

#14


0  

For classes:

类:

The breakthru moment for me was when I learned about interfaces. The idea of abstracting away the details of how you wrote solved a problem, and giving just a list of methods that interact with the class was very insightful.

对我来说,突破的时刻是我学习接口的时候。抽象出如何编写的细节解决了一个问题,并给出与类交互的方法列表的想法非常有见地。

In fact, my professor explicitly told us that he would grade our programs by plugging our classes into his test harness. Grading would be done based on the requirements he gave to us and whether the program crashed.

事实上,我的教授明确地告诉我们,他会把我们的课程插入到他的测试设备中,从而给我们的项目打分。根据他给我们的要求和程序是否崩溃,分级将会完成。

Long story short, classes let you wrap up functionality and call it in a cleaner manner (most of the time, there are always exceptions)

长话短说,类允许您包装功能并以更简洁的方式调用它(大多数时候,总是有例外)

#15


0  

The book that cracked pointers for me was Illustrating Ansi C by Donald Alcock. Its full of hand-drawn-style box and arrow diagrams that illustrate pointers, pointer arithmetic, arrays, string functions etc...

给我打开指针的那本书是唐纳德·阿尔科克(Donald Alcock)的《Ansi C》(Ansi C)的插图。它充满了手工绘制的框和箭头图,这些图说明了指针、指针算法、数组、字符串函数等。

Obviously its a 'C' book but for core fundamentals its hard to beat

显然,这是一本“C”字的书,但就核心基本面而言,它很难被超越

#16


0  

One of the things that really helped me understand these concepts is to learn UML - the Unified Modeling Language. Seeing concepts of object-oriented design in a graphical format really helped me learn what they mean. Sometimes trying to understand these concepts purely by looking at what source code implements them can be difficult to comprehend.

真正帮助我理解这些概念的事情之一是学习UML——统一建模语言。在图形格式中看到面向对象设计的概念确实帮助我了解它们的含义。有时候纯粹通过源代码实现这些概念是很难理解的。

Seeing object-oriented paradigms like inheritance in graphical form is a very powerful way to grasp the concept.

看到面向对象的范例如图形形式的继承是理解概念的一种非常强大的方式。

Martin Fowler's UML Distilled is a good, brief introduction.

Martin Fowler的UML精粹是一个很好的简要介绍。

#17


0  

From lassevek's response to a similar question on SO:

来自lassevek对类似问题的回答:

Pointers is a concept that for many can be confusing at first, in particular when it comes to copying pointer values around and still referencing the same memory block.

指针是一个概念,很多人一开始可能会感到困惑,尤其是当指针值被复制并仍然引用相同的内存块时。

I've found that the best analogy is to consider the pointer as a piece of paper with a house address on it, and the memory block it references as the actual house. All sorts of operations can thus be easily explained:

我发现最好的类比是把指针当作一张纸,上面有一个房子的地址,而内存块则作为实际的房子。因此可以很容易地解释各种操作:

  • Copy pointer value, just write the address on a new piece of paper
  • 复制指针值,把地址写在一张新的纸上。
  • Linked lists, piece of paper at the house with the address of the next house on it
  • 链表,一张写着隔壁房子地址的纸
  • Freeing the memory, demolish the house and erase the address
  • 释放内存,拆除房子,删除地址。
  • Memory leak, you lose the piece of paper and cannot find the house
  • 内存泄露,你丢失了一张纸,找不到房子
  • Freeing the memory but keeping a (now invalid) reference, demolish the house, erase one of the pieces of paper but have another piece of paper with the old address on it, when you go to the address, you won't find a house, but you might find something that resembles the ruins of one
  • 释放内存,但保持(现在是无效的)参考,拆除,抹去一个纸片,但另一个纸上的旧地址,当你去解决,你不会找到一个房子,但是,您可能会发现类似的废墟
  • Buffer overrun, you move more stuff into the house than you can possibly fit, spilling into the neighbours house
  • 缓冲区溢出,你把更多的东西搬到房子里,而不是你能适应的,溢出到邻居的房子里。

#18


0  

Pretend a pointer is an array address.

假设指针是一个数组地址。

x = 500; // memory address for hello;
MEMORY[x] = "hello"; 
print  MEMORY[x]; 

its a graphic oversimplification, but for the most part as long as you never want to know what that number is or set it by hand you should be fine.

这是一种过分简化的图形,但在大多数情况下,只要你不想知道那个数字是什么,或者用手工设置,你应该没问题。

Back when I understood C I had a few macros I had which more or less permitted you to use pointers just like they were an array index in memory. But I've long since lost that code and long since forgotten.

在我理解C的时候,我有一些宏,我有多少允许你使用指针,就像它们是内存中的数组索引一样。但我很久以前就丢失了那个代码,很久以前就忘记了。

I recall it started with

我记得一开始

#define MEMORY 0; 
#define MEMORYADDRESS( a ) *a;

and that on its own is hardly useful. Hopefully somebody else can expand on that logic.

这本身就没什么用。希望其他人也能扩展这个逻辑。

#19


0  

Classes are relatively easy to grasp; OOP can take you many years. Personally, I didn't fully grasp true OOP until last year-ish. It is too bad that Smalltalk isn't as widespread in colleges as it should be. It really drives home the point that OOP is about objects trading messages, instead of classes being self-contained global variables with functions.

班级比较容易掌握;OOP会花你很多年的时间。我个人直到去年才完全掌握OOP。糟糕的是,Smalltalk在大学里并不像它应该的那样普遍。它真正说明了OOP是关于对象交换消息的,而不是具有函数的自包含全局变量的类。

If you truly are new to classes, then the concept can take a while to grasp. When I first encountered them in 10th grade, I didn't get it until I had someone who knew what they were doing step through the code and explain what was going on. That is what I suggest you try.

如果你真的是一个新手,那么这个概念需要一段时间才能掌握。当我第一次遇到他们是在10年级的时候,直到有人知道他们在做什么,我才明白他们在做什么。我建议你试试。

#20


0  

To better understand pointers, I think, it may be useful to look at how the assembly language works with pointers. The concept of pointers is really one of the fundamental parts of the assembly language and x86 processor instruction architecture. Maybe it'll kind of let you fell like pointers are a natural part of a program.

为了更好地理解指针,我认为,看看汇编语言如何使用指针可能是有用的。指针的概念实际上是汇编语言和x86处理器指令体系结构的基本部分之一。也许它会让你觉得指针是程序的一部分。

As to classes, aside from the OO paradigm I think it may be interesting to look at classes from a low-level binary perspective. They aren't that complex in this respect on the basic level.

至于类,除了OO范式之外,我认为从低级二进制的角度来看类可能很有趣。在这个基础层面上,它们并没有那么复杂。

You may read Inside the C++ Object Model if you want to get a better understanding of what is underneath C++ object model.

如果您想更好地理解c++对象模型下面的内容,可以阅读c++对象模型。

#21


0  

The point at which I really got pointers was coding TurboPascal on a FatMac (around 1984 or so) - which was the native Mac language at the time.

我真正得到指针的地方是在一个FatMac上编码涡轮调压机(大约在1984年左右)——当时它是本地的Mac语言。

The Mac had an odd memory model whereby when allocated the address the memory was stored in a pointer on the heap, but the location of that itself was not guaranteed and instead the memory handling routines returned a pointer to the pointer - referred to as a handle. Consequently to access any part of the allocated memory it was necessary to dereference the handle twice. It took a while, but constant practice eventually drove the lesson home.

Mac有一个奇怪的内存模型,当分配地址时,内存被存储在堆上的一个指针中,但是内存本身的位置并没有得到保证,相反,内存处理例程返回一个指向指针的指针——称为句柄。因此,要访问已分配的内存的任何部分,就必须取消两次处理。这花了一段时间,但是不断的练习最终把课程带回家了。

Pascal's pointer handling is easier to grasp than C++, where the syntax doesn't help the beginner. If you are really and truly stuck understanding pointers in C then your best option might be to obtain a copy a a Pascal compiler and try writing some basic pointer code in it (Pascal is near enough to C you'll get the basics in a few hours). Linked lists and the like would be a good choice. Once you're comfortable with those return to C++ and with the concepts mastered you'll find that the cliff won't look so steep.

Pascal的指针处理比c++更容易掌握,因为c++的语法对初学者没有帮助。如果你真的非常理解C语言中的指针,那么你最好的选择可能是获得一个副本一个Pascal编译器,并尝试在其中编写一些基本的指针代码(Pascal语言接近C语言,您将在几小时内获得基础)。链表之类的是一个不错的选择。一旦你习惯了回到c++,并且掌握了这些概念,你就会发现悬崖看起来并不那么陡峭。

#22


0  

Did you read Bjarne Stroustrup's The C++ Programming Language? He created C++.

你读过Bjarne Stroustrup的c++编程语言吗?他创造了c++。

The C++ FAQ Lite is also good.

c++ FAQ Lite也不错。

#23


0  

For pointers and classes, here is my analogy. I'll use a deck of cards. The deck of cards has a face value and a type (9 of hearts, 4 of spades, etc.). So in our C++ like programming language of "Deck of Cards" we'll say the following:

对于指针和类,这里是我的类比。我会用一副牌。纸牌有一个面值和类型(9个红心,4个黑桃,等等)。所以在我们的c++编程语言“纸牌牌堆”中,我们会说:

HeartCard card = 4; // 4 of hearts!

Now, you know where the 4 of hearts is because by golly, you're holding the deck, face up in your hand, and it's at the top! So in relation to the rest of the cards, we'll just say the 4 of hearts is at BEGINNING. So, if I asked you what card is at BEGINNING, you would say, "The 4 of hearts of course!". Well, you just "pointed" me to where the card is. In our "Deck of Cards" programming language, you could just as well say the following:

现在,你知道红心4的位置了因为天哪,你拿着牌面朝上,它在顶部!所以对于剩下的牌,我们只说红心4在开始。所以,如果我问你一开始是什么牌,你会说,“四颗心当然!”你只要把我指给我看那张牌在哪。在我们的“牌堆”编程语言中,您不妨这样说:

HeartCard card = 4; // 4 of hearts!
print &card // the address is BEGINNING!

Now, turn your deck of cards over. The back side is now BEGINNING and you don't know what the card is. But, let's say you can make it whatever you want because you're full of magic. Let's do this in our "Deck of Cards" langauge!

现在,把牌翻过来。背面现在开始了,你不知道牌是什么。但是,假设你可以做任何你想要的因为你充满了魔力。让我们在“纸牌”中做这个!

HeartCard *pointerToCard = MakeMyCard( "10 of hearts" );
print pointerToCard // the value of this is BEGINNING!
print *pointerToCard // this will be 10 of hearts!

Well, MakeMyCard( "10 of hearts" ) was you doing your magic and knowing that you wanted to point to BEGINNING, making the card a 10 of hearts! You turn your card over and, voila! Now, the * may throw you off. If so, check this out:

嗯,MakeMyCard(“10颗心”)是你在做你的魔术,知道你想要开始,让卡片成为10颗心!你把牌转过来,瞧!现在,*可能会把你甩了。如果是的话,看看这个:

HeartCard *pointerToCard = MakeMyCard( "10 of hearts" );
HeartCard card = 4; // 4 of hearts!
print *pointerToCard; // prints 10 of hearts
print pointerToCard; // prints BEGINNING
print card; // prints 4 of hearts
print &card; // prints END - the 4 of hearts used to be on top but we flipped over the deck!

As for classes, we've been using classes in the example by defining a type as HeartCard. We know what a HeartCard is... It's a card with a value and the type of heart! So, we've classified that as a HeartCard. Each language has a similar way of defining or "classifying" what you want, but they all share the same concept! Hope this helped...

至于类,我们在示例中使用了类,方法是将类型定义为HeartCard。我们知道什么是心卡……这是一张有价值、有爱心的卡片!我们把它归类为一张心脏卡。每种语言都有类似的定义或“分类”你想要的东西,但是它们都有相同的概念!希望这有助于……

#24


0  

You may find this article by Joel instructive. As an aside, if you've been "working in C++ for some time" and have graduated in CS, you may have gone to a JavaSchool (I'd argue that you haven't been working in C++ at all; you've been working in C but using the C++ compiler).

你可能会发现这篇文章是由Joel指导的。顺便说一句,如果你已经“在c++工作了一段时间”并且毕业于CS,你可能已经去了一个javascript(我认为你根本没有在c++工作过;您一直在使用C语言,但是使用c++编译器)。

Also, just to second the answers of hojou and nsanders, pointers are very fundamental to C++. If you don't understand pointers, then you don't understand the basics of C++ (acknowledging this fact is the beginning of understanding C++, by the way). Similarly, if you don't understand classes, then you don't understand the basics of C++ (or OO for that matter).

另外,仅仅是hojou和nsanders的回答,指针对于c++来说是非常重要的。如果您不理解指针,那么您就不理解c++的基本知识(顺便说一下,认识到这一点是理解c++的开始)。类似地,如果您不理解类,那么您就不理解c++(或者OO)的基础知识。

For pointers, I think drawing with boxes is a fine idea, but working in assembly is also a good idea. Any instructions that use relative addressing will get you to an understanding of what pointers are rather quickly, I think.

对于指针,我认为使用方框绘图是一个好主意,但是在汇编语言中工作也是一个好主意。我认为,任何使用相对寻址的指令都会让您很快地理解指针是什么。

As for classes (and object-oriented programming more generally), I would recommend Stroustrups "The C++ Programming Language" latest edition. Not only is it the canonical C++ reference material, but it also has quite a bit of material on a lot of other things, from basic object-oriented class hierarchies and inheritance all the way up to design principles in large systems. It's a very good read (if not a little thick and terse in spots).

至于类(和更一般的面向对象编程),我推荐Stroustrups“c++编程语言”的最新版本。它不仅是标准的c++参考资料,而且在许多其他方面也有相当多的资料,从基本的面向对象类层次结构和继承到大型系统的设计原则。这是一本很好的读物(如果不是有点厚的话,在某些地方也很简洁)。

#25


0  

Pointers are not some sort of magical stuff, you're using them all the time!
When you say:

指针不是什么神奇的东西,你一直在用它们!当你说:

int a;

int;

and the compiler generates storage for 'a', you're practically saying that you're declaring
an int and you want to name its memory location 'a'.

编译器为a生成存储,你实际上是在说你在声明一个int类型你想给它的内存命名为a。

When you say:

当你说:

int *a;

int *;

you're declaring a variable that can hold a memory location of an int. It's that simple. Also, don't be scared about pointer arithmetics, just always have in mind a "memory map" when you're dealing with pointers and think in terms of walking through memory addresses.

您正在声明一个变量,它可以保存int的内存位置。另外,不要害怕指针算术,在处理指针时要记住一个“内存映射”,并考虑在内存地址中行走。

Classes in C++ are just one way of defining abstract data types. I'd suggest reading a good OOP book to understand the concept, then, if you're interested, learn how C++ compilers generate code to simulate OOP. But this knowledge will come in time, if you stick with C++ long enough :)

c++中的类只是定义抽象数据类型的一种方式。我建议阅读一本好的OOP书籍来理解这个概念,然后,如果您感兴趣,可以学习c++编译器如何生成代码来模拟OOP。但如果你坚持使用c++足够长时间,这种知识迟早会出现的:

#26


0  

In a sense, you can consider "pointers" to be one of the two most fundamental types in software - the other being "values" (or "data") - that exist in a huge block of uniquely-addressable memory locations. Think about it. Objects and structs etc don't really exist in memory, only values and pointers do. In fact, a pointer is a value too....the value of a memory address, which in turn contains another value....and so on.

在某种意义上,您可以将“指针”视为软件中最基本的两种类型之一——另一种是“值”(或“数据”),它们存在于一大堆惟一可寻址的内存位置中。想想。对象和结构等不存在于内存中,只有值和指针可以。事实上,一个指针也是一个值....内存地址的值,进而包含另一个值....等等。

So, in C/C++, when you declare an "int" (intA), you are defining a 32bit chunk of memory that contains a value - a number. If you then declare an "int pointer" (intB), you are defining a 32bit chunk of memory that contains the address of an int. I can assign the latter to point to the former by stating "intB = &intA", and now the 32bits of memory defined as intB, contains an address corresponding to intA's location in memory.

因此,在C/ c++中,当您声明一个“int”(intA)时,您正在定义一个包含值-数字的32位内存块。如果你声明一个“int指针”(intB),你定义一个32位的内存块,它包含一个int的地址。我可以分配后者指向前说“intB = intA”,现在的32位内存定义为intB,包含一个地址对应落脚的位置在内存中。

When you "dereference" the intB pointer, you are looking at the address stored within intB's memory, finding that location, and then looking at the value stored there (a number).

当您“取消引用”intB指针时,您正在查看存储在intB内存中的地址,找到那个位置,然后查看存储在那里的值(一个数字)。

Commonly, I have encountered confusion when people lose track of exactly what it is they're dealing with as they use the "&", "*" and "->" operators - is it an address, a value or what? You just need to keep focused on the fact that memory addresses are simply locations, and that values are the binary information stored there.

通常,当人们在使用“&”、“*”和“->”操作符时,不知道自己在处理什么时,我就会感到困惑,这是一个地址、一个值还是什么?您只需要关注这样一个事实:内存地址仅仅是位置,值是存储在那里的二进制信息。

#27


0  

Your problem seems to be the C core in C++, not C++ itself. Get yourself the Kernighan & Ritchie (The C Programming Language). Inhale it. It's very good stuff, one of the best programming language books ever written.

您的问题似乎是c++中的C核心,而不是c++本身。为自己准备好Kernighan & Ritchie (C编程语言)。吸入。这是非常好的东西,是有史以来最好的编程语言书籍之一。

#1


19  

Understanding Pointers in C/C++

在C / c++理解指针

Before one can understand how pointers work, it is necessary to understand how variables are stored and accessed in programs. Every variable has 2 parts to it - (1) the memory address where the data is stored and (2) the value of the data stored.

在理解指针如何工作之前,有必要了解如何在程序中存储和访问变量。每个变量都有两个部分—(1)存储数据的内存地址和(2)存储数据的值。

The memory address is often referred to as the lvalue of a variable, and the value of the data stored is referred to as the rvalue (l and r meaning left and right).

内存地址通常被称为变量的lvalue,存储的数据的值被称为rvalue (l和r分别表示左和右)。

Consider the statement:

考虑语句:

int x = 10;

Internally, the program associates a memory address with the variable x. In this case, let's assume that the program assigns x to reside at the address 1001 (not a realistic address, but chosen for simplicity). Therefore, the lvalue (memory address) of x is 1001, and the rvalue (data value) of x is 10.

在内部,程序将一个内存地址与变量x关联。在本例中,我们假设程序将x分配到地址1001(不是一个实际的地址,而是为了简单起见而选择的)。因此,x的lvalue(内存地址)为1001,x的rvalue(数据值)为10。

The rvalue is accessed by simply using the variable “x”. In order to access the lvalue, the “address of” operator (‘&’) is needed. The expression ‘&x’ is read as "the address of x".

只要使用变量“x”就可以访问rvalue。为了访问lvalue,需要操作符(' & ')的“地址”。表达式' &x '被读为" x的地址"。

Expression          Value
----------------------------------
x                   10
&x                  1001

The value stored in x can be changed at any time (e.g. x = 20), but the address of x (&x) can never be changed.

存储在x中的值可以随时更改(例如x = 20),但是x (&x)的地址永远不能更改。

A pointer is simply a variable that can be used to modify another variable. It does this by having a memory address for its rvalue. That is, it points to another location in memory.

指针只是一个可以用来修改另一个变量的变量。它通过为其rvalue设置一个内存地址来实现这一点。也就是说,它指向内存中的另一个位置。

Creating a pointer to “x” is done as follows:

创建指向“x”的指针如下所示:

int* xptr = &x;

The “int*” tells the compiler that we are creating a pointer to an integer value. The “= &x” part tells the compiler that we are assigning the address of x to the rvalue of xptr. Thus, we are telling the compiler that xptr “points to” x.

“int*”告诉编译器我们正在创建一个指向整数值的指针。“= &x”部分告诉编译器我们正在将x的地址赋给xptr的rvalue。因此,我们告诉编译器xptr指向“x”。

Assuming that xptr is assigned to a memory address of 1002, then the program’s memory might look like this:

假设xptr被分配到1002的内存地址,那么程序的内存可能是这样的:

Variable    lvalue    rvalue
--------------------------------------------
x           1001      10   
xptr        1002      1001

The next piece of the puzzle is the "indirection operator" (‘*’), which is used as follows:

下一个难题是“间接运算符”(' * '),它的用法如下:

int y = *xptr;

The indirection operator tells the program to interpret the rvalue of xptr as a memory address rather than a data value. That is, the program looks for the data value (10) stored at the address provided by xptr (1001).

间接运算符告诉程序将xptr的rvalue解释为一个内存地址,而不是一个数据值。即,程序查找存储在xptr(1001)提供的地址中的数据值(10)。

Putting it all together:

把它放在一起:

Expression      Value
--------------------------------------------
x                   10
&x                  1001
xptr                1001
&xptr               1002
*xptr               10

Now that the concepts have been explained, here is some code to demonstrate the power of pointers:

既然已经解释了这些概念,下面的代码演示了指针的威力:

int x = 10;
int *xptr = &x;

printf("x = %d\n", x);
printf("&x = %d\n", &x);        
printf("xptr = %d\n", xptr);
printf("*xptr = %d\n", *xptr);

*xptr = 20;

printf("x = %d\n", x);
printf("*xptr = %d\n", *xptr);

For output you would see (Note: the memory address will be different each time):

对于输出,您将看到(注意:内存地址每次都会不同):

x = 10
&x = 3537176
xptr = 3537176
*xptr = 10
x = 20
*xptr = 20

Notice how assigning a value to ‘*xptr’ changed the value of ‘x’. This is because ‘*xptr’ and ‘x’ refer to the same location in memory, as evidenced by ‘&x’ and ‘xptr’ having the same value.

注意,将值赋给' *xptr '会如何改变' x '的值。这是因为' *xptr '和' x '在内存中表示相同的位置,' &x '和' xptr '具有相同的值。

#2


18  

Pointers and classes aren't really advanced topics in C++. They are pretty fundamental.

在c++中,指针和类并不是真正的高级主题。他们是很基本的。

For me, pointers solidified when I started drawing boxes with arrows. Draw a box for an int. And int* is now a separate box with an arrow pointing to the int box.

对我来说,当我开始用箭头画盒子的时候,指针就凝固了。绘制一个int型的方框。int*现在是一个单独的方框,箭头指向int型方框。

So:

所以:

int foo = 3;           // integer
int* bar = &foo;       // assigns the address of foo to my pointer bar

With my pointer's box (bar) I have the choice of either looking at the address inside the box. (Which is the memory address of foo). Or I can manipulate whatever I have an address to. That manipulation means I'm following that arrow to the integer (foo).

使用我的指针的框(栏),我可以选择查看盒子里面的地址。(是foo的内存地址)或者我可以操纵我的地址。这个操作意味着我沿着箭头指向整型(foo)

*bar = 5;  // asterix means "dereference" (follow the arrow), foo is now 5
bar = 0;   // I just changed the address that bar points to

Classes are another topic entirely. There's some books on object oriented design, but I don't know good ones for beginners of the top of my head. You might have luck with an intro Java book.

课程完全是另一个主题。有一些关于面向对象设计的书,但是我不知道适合我的头顶初学者的书。你可能会有一本介绍Java的书。

#3


7  

This link has a video describing how pointers work, with claymation. Informative, and easy to digest.

这个链接有一个视频描述指针是如何工作的,用的是claymation。内容丰富,易于理解。

This page has some good information on the basic of classes.

这个页面有一些关于基本类的好信息。

#4


4  

I used to have a problem understand pointers in pascal way back :) Once i started doing assembler pointers was really the only way to access memory and it just hit me. It might sound like a far shot, but trying out assembler (which is always a good idea to try and understand what computers is really about) probably will teach you pointers. Classes - well i don't understand your problem - was your schooling pure structured programming? A class is just a logical way of looking at real life models - you're trying to solve a problem which could be summed up in a number of objects/classes.

我曾经遇到过这样的问题,理解pascal语言中的指针:)一旦我开始做汇编指针,它真的是访问内存的唯一方法,它就会击中我。这听起来可能有点遥不可及,但尝试汇编程序(尝试理解计算机的真正含义总是一个好主意)可能会教会您指针。课堂——我不明白你的问题——你的学校是纯粹的结构化编程吗?一个类仅仅是观察现实生活模型的一种逻辑方法——你正在尝试解决一个问题,这个问题可以在一些对象/类中进行总结。

#5


3  

Pointers and classes are completely different topics so I wouldn't really lump them in together like this. Of the two, I would say pointers are more fundamental.

指针和类是完全不同的主题,所以我不会像这样把它们放在一起。在这两者中,指针是最基本的。

A good exercise for learning about what pointers are is the following:

下面是一个很好的练习来学习什么是指针:

  1. create a linked list
  2. 创建一个链表
  3. iterate through it from start to finish
  4. 从头到尾遍历它。
  5. reverse it so that the head is now the back and the back is now the head
  6. 倒转它,使头部现在是背面,背面现在是头部

Do it all on a whiteboard first. If you can do this easily, you should have no more problems understanding what pointers are.

首先在白板上做这些。如果你能很容易地做到这一点,你就不会有任何问题去理解指针是什么了。

#6


2  

Pointers already seem to be addressed (no pun intended) in other answers.

指针似乎已经在其他答案中被提及(没有双关语意思)。

Classes are fundamental to OO. I had tremendous trouble wrenching my head into OO - like, ten years of failed attempts. The book that finally helped me was Craig Larman's "Applying UML and Patterns". I know it sounds as if it's about something different, but it really does a great job of easing you into the world of classes and objects.

类是OO的基础。我绞尽脑汁,绞尽脑汁,想了10年的失败尝试。最终帮助我的书是Craig Larman的《应用UML和模式》。我知道这听起来好像是关于一些不同的东西,但它确实很好地让你进入了类和对象的世界。

#7


2  

We were just discussing some of the aspects of C++ and OO at lunch, someone (a great engineer actually) was saying that unless you have a really strong programming background before you learn C++, it will literally ruin you.

我们刚刚在午餐时间讨论了c++和OO的一些方面,有人(实际上是一位伟大的工程师)说,除非你在学习c++之前有非常强的编程背景,否则它会毁了你。

I highly recommend learning another language first, then shifting to C++ when you need it. It's not like there is anything great about pointers, they are simply a vestigial piece left over from when it was difficult for a compiler convert operations to assembly efficiently without them.

我强烈建议先学习另一种语言,然后在需要的时候转向c++。这并不是说指针有什么了不起的地方,它们只是一个遗留的片段,当编译器很难在没有它们的情况下有效地将操作转换为程序集时,它们就会被遗留下来。

These days if a compiler can't optimize an array operation better then you can using pointers, your compiler is broken.

现在,如果编译器不能更好地优化数组操作,那么就可以使用指针,那么编译器就坏了。

Please don't get me wrong, I'm not saying C++ is horrible or anything and don't want to start an advocacy discussion, I've used it and use it occasionally now, I'm just recommending you start with something else.

请不要误解我的意思,我并不是说c++很可怕或者其他什么,我也不想开始一场倡导性的讨论,我已经用过它了,现在偶尔用一下,我只是建议你从别的东西开始。

It's really NOT like learning to drive a manual car then easily being able to apply that to an automatic, it's more like learning to drive on one of those huge construction cranes then assuming that will apply when you start to drive a car--then you find yourself driving your car down the middle of the street at 5mph with your emergency lights on.

真的很不喜欢学习开手动车那么容易能够应用到自动,它更像是学开车在一个巨大的建筑起重机假设将当你开始开车,那么你会发现自己开车的*大街在5英里每小时和你紧急照明设备。

[edit] reviewing that last paragraph--I think that may have been my most accurate analogy ever!

[编辑]回顾最后一段——我认为这可能是我做过的最准确的类比!

#8


1  

To understand pointers, I can't recommend the K&R book highly enough.

要理解指针,我无法向您推荐K&R这本书。

#9


1  

For Pointers:

指针:

I found this post had very thoughtful discussion about pointers. Maybe that would help. Are you familar with refrences such as in C#? That is something that actually refers to something else? Thats probably a good start for understanding pointers.

我发现这篇文章对指针进行了非常深入的讨论。也许会有所帮助。你熟悉c#之类的折射率吗?这实际上是指其他的东西?这可能是理解指针的良好开端。

Also, look at Kent Fredric's post below on another way to introduce yourself to pointers.

另外,看看下面Kent Fredric的文章,介绍一下指针。

#10


1  

Learn assembly language and then learn C. Then you will know what the underlying principles of machine are (and thefore pointers).

学习汇编语言,然后学习c语言,这样你就会知道机器的基本原理是什么(以及前面的指针)。

Pointers and classes are fundamental aspects of C++. If you don't understand them then it means that you don't really understand C++.

指针和类是c++的基本方面。如果你不理解它们,那就意味着你不理解c++。

Personally I held back on C++ for several years until I felt I had a firm grasp of C and what was happening under the hood in assembly language. Although this was quite a long time ago now I think it really benefited my career to understand how the computer works at a low-level.

就我个人而言,几年来我一直对c++持保留态度,直到我觉得自己对C有了牢固的掌握,以及汇编语言背后发生的事情。虽然这是很久以前的事了,但现在我认为我的职业生涯确实受益于计算机在低水平的工作。

Learning to program can take many years, but you should stick with it because it is a very rewarding career.

学习编程可能需要很多年的时间,但你应该坚持下去,因为这是一个非常有益的职业。

#11


1  

There's no substiture for practicing.

没有进行练习的技巧。

It's easy to read through a book or listen to a lecture and feel like you're following what's going on.

读一本书或听一场讲座很容易,你会觉得自己在听。

What I would recommend is taking some of the code examples (I assume you have them on disk somewhere), compile them and run them, then try to change them to do something different.

我建议您使用一些代码示例(我假设您在磁盘上有它们),编译并运行它们,然后尝试更改它们以执行一些不同的操作。

  • Add another subclass to a hierarchy
  • 向层次结构添加另一个子类
  • Add a method to an existing class
  • 向现有类添加方法
  • Change an algorithm that iterates forward through a collection to go backward instead.
  • 更改在集合中向前迭代的算法,改为向后迭代。

I don't think there's any "silver bullet" book that's going to do it.

我不认为有什么“银弹”的书能做到这一点。

For me, what drove home what pointers meant was working in assembly, and seeing that a pointer was actually just an address, and that having a pointer didn't mean that what it pointed to was a meaningful object.

对我来说,指针的意义在于在汇编中工作,看到指针实际上只是一个地址,而拥有指针并不意味着它指向的是一个有意义的对象。

#12


1  

In the case of classes I had three techniques that really helped me make the jump into real object oriented programming.

在类的例子中,我有三种技术可以帮助我进入真正的面向对象编程。

The first was I worked on a game project that made heavy use of classes and objects, with heavy use of generalization (kind-of or is-a relationship, ex. student is a kind of person) and composition (has-a relationship, ex. student has a student loan). Breaking apart this code took a lot of work, but really brought things into perspective.

第一个是我在一个游戏项目中大量使用类和对象,大量使用泛化(类的或is的)关系,例如,学生是一种人)和构成(类的关系,例如,学生有学生贷款)。分解这段代码需要花费大量的工作,但真正让事情变得有意义。

The second thing that helped was in my System Analysis class, where I had to make http://www.agilemodeling.com/artifacts/classDiagram.htm">UML class diagrams. These I just really found helped me understand the structure of classes in a program.

第二件有帮助的事情是在我的系统分析类中,我必须创建http://www.agilemodeling.com/artifacts/classDiagram.htm“>UML类图。我刚刚发现的这些帮助我理解了程序中类的结构。

Lastly, I help tutor students at my college in programming. All I can really say about this is you learn a lot by teaching and by seeing other people's approach to a problem. Many times a student will try things that I would never have thought of, but usually make a lot of sense and they just have problems implementing their idea.

最后,我在我的大学里帮助指导学生们编程。我能说的是,通过教学和观察别人解决问题的方法,你能学到很多东西。很多时候,学生都会尝试一些我从未想过的事情,但通常都是很有意义的,他们只是在实现自己的想法时遇到了问题。

My best word of advice is it takes a lot of practice, and the more you program the better you will understand it.

我最好的建议是,这需要大量的练习,编程越多,你就越能理解它。

#13


0  

The best book I've read on these topics is Thinking in C++ by Bruce Eckel. You can download it for free here.

关于这些话题,我读过的最好的书是布鲁斯·埃克尔(Bruce Eckel)的《用c++思考》(Thinking in c++)。你可以在这里免费下载。

#14


0  

For classes:

类:

The breakthru moment for me was when I learned about interfaces. The idea of abstracting away the details of how you wrote solved a problem, and giving just a list of methods that interact with the class was very insightful.

对我来说,突破的时刻是我学习接口的时候。抽象出如何编写的细节解决了一个问题,并给出与类交互的方法列表的想法非常有见地。

In fact, my professor explicitly told us that he would grade our programs by plugging our classes into his test harness. Grading would be done based on the requirements he gave to us and whether the program crashed.

事实上,我的教授明确地告诉我们,他会把我们的课程插入到他的测试设备中,从而给我们的项目打分。根据他给我们的要求和程序是否崩溃,分级将会完成。

Long story short, classes let you wrap up functionality and call it in a cleaner manner (most of the time, there are always exceptions)

长话短说,类允许您包装功能并以更简洁的方式调用它(大多数时候,总是有例外)

#15


0  

The book that cracked pointers for me was Illustrating Ansi C by Donald Alcock. Its full of hand-drawn-style box and arrow diagrams that illustrate pointers, pointer arithmetic, arrays, string functions etc...

给我打开指针的那本书是唐纳德·阿尔科克(Donald Alcock)的《Ansi C》(Ansi C)的插图。它充满了手工绘制的框和箭头图,这些图说明了指针、指针算法、数组、字符串函数等。

Obviously its a 'C' book but for core fundamentals its hard to beat

显然,这是一本“C”字的书,但就核心基本面而言,它很难被超越

#16


0  

One of the things that really helped me understand these concepts is to learn UML - the Unified Modeling Language. Seeing concepts of object-oriented design in a graphical format really helped me learn what they mean. Sometimes trying to understand these concepts purely by looking at what source code implements them can be difficult to comprehend.

真正帮助我理解这些概念的事情之一是学习UML——统一建模语言。在图形格式中看到面向对象设计的概念确实帮助我了解它们的含义。有时候纯粹通过源代码实现这些概念是很难理解的。

Seeing object-oriented paradigms like inheritance in graphical form is a very powerful way to grasp the concept.

看到面向对象的范例如图形形式的继承是理解概念的一种非常强大的方式。

Martin Fowler's UML Distilled is a good, brief introduction.

Martin Fowler的UML精粹是一个很好的简要介绍。

#17


0  

From lassevek's response to a similar question on SO:

来自lassevek对类似问题的回答:

Pointers is a concept that for many can be confusing at first, in particular when it comes to copying pointer values around and still referencing the same memory block.

指针是一个概念,很多人一开始可能会感到困惑,尤其是当指针值被复制并仍然引用相同的内存块时。

I've found that the best analogy is to consider the pointer as a piece of paper with a house address on it, and the memory block it references as the actual house. All sorts of operations can thus be easily explained:

我发现最好的类比是把指针当作一张纸,上面有一个房子的地址,而内存块则作为实际的房子。因此可以很容易地解释各种操作:

  • Copy pointer value, just write the address on a new piece of paper
  • 复制指针值,把地址写在一张新的纸上。
  • Linked lists, piece of paper at the house with the address of the next house on it
  • 链表,一张写着隔壁房子地址的纸
  • Freeing the memory, demolish the house and erase the address
  • 释放内存,拆除房子,删除地址。
  • Memory leak, you lose the piece of paper and cannot find the house
  • 内存泄露,你丢失了一张纸,找不到房子
  • Freeing the memory but keeping a (now invalid) reference, demolish the house, erase one of the pieces of paper but have another piece of paper with the old address on it, when you go to the address, you won't find a house, but you might find something that resembles the ruins of one
  • 释放内存,但保持(现在是无效的)参考,拆除,抹去一个纸片,但另一个纸上的旧地址,当你去解决,你不会找到一个房子,但是,您可能会发现类似的废墟
  • Buffer overrun, you move more stuff into the house than you can possibly fit, spilling into the neighbours house
  • 缓冲区溢出,你把更多的东西搬到房子里,而不是你能适应的,溢出到邻居的房子里。

#18


0  

Pretend a pointer is an array address.

假设指针是一个数组地址。

x = 500; // memory address for hello;
MEMORY[x] = "hello"; 
print  MEMORY[x]; 

its a graphic oversimplification, but for the most part as long as you never want to know what that number is or set it by hand you should be fine.

这是一种过分简化的图形,但在大多数情况下,只要你不想知道那个数字是什么,或者用手工设置,你应该没问题。

Back when I understood C I had a few macros I had which more or less permitted you to use pointers just like they were an array index in memory. But I've long since lost that code and long since forgotten.

在我理解C的时候,我有一些宏,我有多少允许你使用指针,就像它们是内存中的数组索引一样。但我很久以前就丢失了那个代码,很久以前就忘记了。

I recall it started with

我记得一开始

#define MEMORY 0; 
#define MEMORYADDRESS( a ) *a;

and that on its own is hardly useful. Hopefully somebody else can expand on that logic.

这本身就没什么用。希望其他人也能扩展这个逻辑。

#19


0  

Classes are relatively easy to grasp; OOP can take you many years. Personally, I didn't fully grasp true OOP until last year-ish. It is too bad that Smalltalk isn't as widespread in colleges as it should be. It really drives home the point that OOP is about objects trading messages, instead of classes being self-contained global variables with functions.

班级比较容易掌握;OOP会花你很多年的时间。我个人直到去年才完全掌握OOP。糟糕的是,Smalltalk在大学里并不像它应该的那样普遍。它真正说明了OOP是关于对象交换消息的,而不是具有函数的自包含全局变量的类。

If you truly are new to classes, then the concept can take a while to grasp. When I first encountered them in 10th grade, I didn't get it until I had someone who knew what they were doing step through the code and explain what was going on. That is what I suggest you try.

如果你真的是一个新手,那么这个概念需要一段时间才能掌握。当我第一次遇到他们是在10年级的时候,直到有人知道他们在做什么,我才明白他们在做什么。我建议你试试。

#20


0  

To better understand pointers, I think, it may be useful to look at how the assembly language works with pointers. The concept of pointers is really one of the fundamental parts of the assembly language and x86 processor instruction architecture. Maybe it'll kind of let you fell like pointers are a natural part of a program.

为了更好地理解指针,我认为,看看汇编语言如何使用指针可能是有用的。指针的概念实际上是汇编语言和x86处理器指令体系结构的基本部分之一。也许它会让你觉得指针是程序的一部分。

As to classes, aside from the OO paradigm I think it may be interesting to look at classes from a low-level binary perspective. They aren't that complex in this respect on the basic level.

至于类,除了OO范式之外,我认为从低级二进制的角度来看类可能很有趣。在这个基础层面上,它们并没有那么复杂。

You may read Inside the C++ Object Model if you want to get a better understanding of what is underneath C++ object model.

如果您想更好地理解c++对象模型下面的内容,可以阅读c++对象模型。

#21


0  

The point at which I really got pointers was coding TurboPascal on a FatMac (around 1984 or so) - which was the native Mac language at the time.

我真正得到指针的地方是在一个FatMac上编码涡轮调压机(大约在1984年左右)——当时它是本地的Mac语言。

The Mac had an odd memory model whereby when allocated the address the memory was stored in a pointer on the heap, but the location of that itself was not guaranteed and instead the memory handling routines returned a pointer to the pointer - referred to as a handle. Consequently to access any part of the allocated memory it was necessary to dereference the handle twice. It took a while, but constant practice eventually drove the lesson home.

Mac有一个奇怪的内存模型,当分配地址时,内存被存储在堆上的一个指针中,但是内存本身的位置并没有得到保证,相反,内存处理例程返回一个指向指针的指针——称为句柄。因此,要访问已分配的内存的任何部分,就必须取消两次处理。这花了一段时间,但是不断的练习最终把课程带回家了。

Pascal's pointer handling is easier to grasp than C++, where the syntax doesn't help the beginner. If you are really and truly stuck understanding pointers in C then your best option might be to obtain a copy a a Pascal compiler and try writing some basic pointer code in it (Pascal is near enough to C you'll get the basics in a few hours). Linked lists and the like would be a good choice. Once you're comfortable with those return to C++ and with the concepts mastered you'll find that the cliff won't look so steep.

Pascal的指针处理比c++更容易掌握,因为c++的语法对初学者没有帮助。如果你真的非常理解C语言中的指针,那么你最好的选择可能是获得一个副本一个Pascal编译器,并尝试在其中编写一些基本的指针代码(Pascal语言接近C语言,您将在几小时内获得基础)。链表之类的是一个不错的选择。一旦你习惯了回到c++,并且掌握了这些概念,你就会发现悬崖看起来并不那么陡峭。

#22


0  

Did you read Bjarne Stroustrup's The C++ Programming Language? He created C++.

你读过Bjarne Stroustrup的c++编程语言吗?他创造了c++。

The C++ FAQ Lite is also good.

c++ FAQ Lite也不错。

#23


0  

For pointers and classes, here is my analogy. I'll use a deck of cards. The deck of cards has a face value and a type (9 of hearts, 4 of spades, etc.). So in our C++ like programming language of "Deck of Cards" we'll say the following:

对于指针和类,这里是我的类比。我会用一副牌。纸牌有一个面值和类型(9个红心,4个黑桃,等等)。所以在我们的c++编程语言“纸牌牌堆”中,我们会说:

HeartCard card = 4; // 4 of hearts!

Now, you know where the 4 of hearts is because by golly, you're holding the deck, face up in your hand, and it's at the top! So in relation to the rest of the cards, we'll just say the 4 of hearts is at BEGINNING. So, if I asked you what card is at BEGINNING, you would say, "The 4 of hearts of course!". Well, you just "pointed" me to where the card is. In our "Deck of Cards" programming language, you could just as well say the following:

现在,你知道红心4的位置了因为天哪,你拿着牌面朝上,它在顶部!所以对于剩下的牌,我们只说红心4在开始。所以,如果我问你一开始是什么牌,你会说,“四颗心当然!”你只要把我指给我看那张牌在哪。在我们的“牌堆”编程语言中,您不妨这样说:

HeartCard card = 4; // 4 of hearts!
print &card // the address is BEGINNING!

Now, turn your deck of cards over. The back side is now BEGINNING and you don't know what the card is. But, let's say you can make it whatever you want because you're full of magic. Let's do this in our "Deck of Cards" langauge!

现在,把牌翻过来。背面现在开始了,你不知道牌是什么。但是,假设你可以做任何你想要的因为你充满了魔力。让我们在“纸牌”中做这个!

HeartCard *pointerToCard = MakeMyCard( "10 of hearts" );
print pointerToCard // the value of this is BEGINNING!
print *pointerToCard // this will be 10 of hearts!

Well, MakeMyCard( "10 of hearts" ) was you doing your magic and knowing that you wanted to point to BEGINNING, making the card a 10 of hearts! You turn your card over and, voila! Now, the * may throw you off. If so, check this out:

嗯,MakeMyCard(“10颗心”)是你在做你的魔术,知道你想要开始,让卡片成为10颗心!你把牌转过来,瞧!现在,*可能会把你甩了。如果是的话,看看这个:

HeartCard *pointerToCard = MakeMyCard( "10 of hearts" );
HeartCard card = 4; // 4 of hearts!
print *pointerToCard; // prints 10 of hearts
print pointerToCard; // prints BEGINNING
print card; // prints 4 of hearts
print &card; // prints END - the 4 of hearts used to be on top but we flipped over the deck!

As for classes, we've been using classes in the example by defining a type as HeartCard. We know what a HeartCard is... It's a card with a value and the type of heart! So, we've classified that as a HeartCard. Each language has a similar way of defining or "classifying" what you want, but they all share the same concept! Hope this helped...

至于类,我们在示例中使用了类,方法是将类型定义为HeartCard。我们知道什么是心卡……这是一张有价值、有爱心的卡片!我们把它归类为一张心脏卡。每种语言都有类似的定义或“分类”你想要的东西,但是它们都有相同的概念!希望这有助于……

#24


0  

You may find this article by Joel instructive. As an aside, if you've been "working in C++ for some time" and have graduated in CS, you may have gone to a JavaSchool (I'd argue that you haven't been working in C++ at all; you've been working in C but using the C++ compiler).

你可能会发现这篇文章是由Joel指导的。顺便说一句,如果你已经“在c++工作了一段时间”并且毕业于CS,你可能已经去了一个javascript(我认为你根本没有在c++工作过;您一直在使用C语言,但是使用c++编译器)。

Also, just to second the answers of hojou and nsanders, pointers are very fundamental to C++. If you don't understand pointers, then you don't understand the basics of C++ (acknowledging this fact is the beginning of understanding C++, by the way). Similarly, if you don't understand classes, then you don't understand the basics of C++ (or OO for that matter).

另外,仅仅是hojou和nsanders的回答,指针对于c++来说是非常重要的。如果您不理解指针,那么您就不理解c++的基本知识(顺便说一下,认识到这一点是理解c++的开始)。类似地,如果您不理解类,那么您就不理解c++(或者OO)的基础知识。

For pointers, I think drawing with boxes is a fine idea, but working in assembly is also a good idea. Any instructions that use relative addressing will get you to an understanding of what pointers are rather quickly, I think.

对于指针,我认为使用方框绘图是一个好主意,但是在汇编语言中工作也是一个好主意。我认为,任何使用相对寻址的指令都会让您很快地理解指针是什么。

As for classes (and object-oriented programming more generally), I would recommend Stroustrups "The C++ Programming Language" latest edition. Not only is it the canonical C++ reference material, but it also has quite a bit of material on a lot of other things, from basic object-oriented class hierarchies and inheritance all the way up to design principles in large systems. It's a very good read (if not a little thick and terse in spots).

至于类(和更一般的面向对象编程),我推荐Stroustrups“c++编程语言”的最新版本。它不仅是标准的c++参考资料,而且在许多其他方面也有相当多的资料,从基本的面向对象类层次结构和继承到大型系统的设计原则。这是一本很好的读物(如果不是有点厚的话,在某些地方也很简洁)。

#25


0  

Pointers are not some sort of magical stuff, you're using them all the time!
When you say:

指针不是什么神奇的东西,你一直在用它们!当你说:

int a;

int;

and the compiler generates storage for 'a', you're practically saying that you're declaring
an int and you want to name its memory location 'a'.

编译器为a生成存储,你实际上是在说你在声明一个int类型你想给它的内存命名为a。

When you say:

当你说:

int *a;

int *;

you're declaring a variable that can hold a memory location of an int. It's that simple. Also, don't be scared about pointer arithmetics, just always have in mind a "memory map" when you're dealing with pointers and think in terms of walking through memory addresses.

您正在声明一个变量,它可以保存int的内存位置。另外,不要害怕指针算术,在处理指针时要记住一个“内存映射”,并考虑在内存地址中行走。

Classes in C++ are just one way of defining abstract data types. I'd suggest reading a good OOP book to understand the concept, then, if you're interested, learn how C++ compilers generate code to simulate OOP. But this knowledge will come in time, if you stick with C++ long enough :)

c++中的类只是定义抽象数据类型的一种方式。我建议阅读一本好的OOP书籍来理解这个概念,然后,如果您感兴趣,可以学习c++编译器如何生成代码来模拟OOP。但如果你坚持使用c++足够长时间,这种知识迟早会出现的:

#26


0  

In a sense, you can consider "pointers" to be one of the two most fundamental types in software - the other being "values" (or "data") - that exist in a huge block of uniquely-addressable memory locations. Think about it. Objects and structs etc don't really exist in memory, only values and pointers do. In fact, a pointer is a value too....the value of a memory address, which in turn contains another value....and so on.

在某种意义上,您可以将“指针”视为软件中最基本的两种类型之一——另一种是“值”(或“数据”),它们存在于一大堆惟一可寻址的内存位置中。想想。对象和结构等不存在于内存中,只有值和指针可以。事实上,一个指针也是一个值....内存地址的值,进而包含另一个值....等等。

So, in C/C++, when you declare an "int" (intA), you are defining a 32bit chunk of memory that contains a value - a number. If you then declare an "int pointer" (intB), you are defining a 32bit chunk of memory that contains the address of an int. I can assign the latter to point to the former by stating "intB = &intA", and now the 32bits of memory defined as intB, contains an address corresponding to intA's location in memory.

因此,在C/ c++中,当您声明一个“int”(intA)时,您正在定义一个包含值-数字的32位内存块。如果你声明一个“int指针”(intB),你定义一个32位的内存块,它包含一个int的地址。我可以分配后者指向前说“intB = intA”,现在的32位内存定义为intB,包含一个地址对应落脚的位置在内存中。

When you "dereference" the intB pointer, you are looking at the address stored within intB's memory, finding that location, and then looking at the value stored there (a number).

当您“取消引用”intB指针时,您正在查看存储在intB内存中的地址,找到那个位置,然后查看存储在那里的值(一个数字)。

Commonly, I have encountered confusion when people lose track of exactly what it is they're dealing with as they use the "&", "*" and "->" operators - is it an address, a value or what? You just need to keep focused on the fact that memory addresses are simply locations, and that values are the binary information stored there.

通常,当人们在使用“&”、“*”和“->”操作符时,不知道自己在处理什么时,我就会感到困惑,这是一个地址、一个值还是什么?您只需要关注这样一个事实:内存地址仅仅是位置,值是存储在那里的二进制信息。

#27


0  

Your problem seems to be the C core in C++, not C++ itself. Get yourself the Kernighan & Ritchie (The C Programming Language). Inhale it. It's very good stuff, one of the best programming language books ever written.

您的问题似乎是c++中的C核心,而不是c++本身。为自己准备好Kernighan & Ritchie (C编程语言)。吸入。这是非常好的东西,是有史以来最好的编程语言书籍之一。

相关文章