首页 > 解决方案 > 理解指针

问题描述

我在 Herbert Schildth 写的 c++ 书中找到了这些例子

第一个例子

#include<iostream>
#include<cstring>
#include<new>
using namespace std;
class Balance
{
char name[80];
double cur_bal;
public:
Balance(){}
void set(double n,char *s)
{
    cur_bal=n;
    strcpy(name,s); 
}
void get(double &n,char *s)
{
    n=cur_bal;
    strcpy(s,name);
}
};
int main()
{
Balance *p;
char name[80]; double n;
try{ p= new Balance[2]; }
catch(bad_alloc e){ cout<<"alloctaion Failed\n"; return 1;}
p[0].set(121.50,"harsh");   //using DOT to access member function
p[1].set(221.50,"sparsh");  //using DOT to access member function
p[0].get(n,name);
return 0;
}

第二个例子

#include<iostream>
#include<cstring>
#include<new>
using namespace std;
class balance
{
 double cur_bal;
 char name[80];
 public:
  void set(double n,char *s)
  {
  cur_bal=n;
  strcpy(name,s);
 }
 void get_bal(double &n,char *s)
 {
   n=cur_bal;
   strcpy(s,name);
 }
};
int main()
{
balance *p;
char s[80];
double n;
try{p=new balance;}
catch(bad_alloc e){cout<<"Allocation Failed";  return 1; }
p->set(124.24,"harsh"); // using ARROW to access member function
 p->get_bal(n,s);   // using ARROW to access member function
 return 0;
}

拜托,我不需要两个运算符之间的区别(它已经在指向那个问题的 SO 链接上),而只是简单地解释为什么它们分别使用箭头和点,以及我如何理解何时使用什么?

标签: c++

解决方案


为简单起见,每当您通过指针访问成员(数据成员、成员函数)时,都使用箭头。如果你是通过变量或对象的成员(数据成员、成员函数)然后使用点。例如

int main()
{
    balance b; // Or balance b = new b; (and delete it at the end of program)
    char s[80];
    double n;
    b.set(124.24,"harsh"); // using DOT to access member function
    b.get_bal(n,s);   // using DOT to access member function
    return 0;
}

这里 b 是类 balance 的对象,而不是指向它的指针引用。在您的第一个示例中, p 充当将包含 Balance 类型的对象的对象数组。因此,p 的每个索引都将包含 Balance 类对象,并且成员将由 DOT 运算符访问数组中的每个条目。

在第二个示例中,p 本身是一个指向类余额的指针。所以 Arrow 需要访问成员


推荐阅读