c++ - 理解指针
问题描述
我在 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 链接上),而只是简单地解释为什么它们分别使用箭头和点,以及我如何理解何时使用什么?
解决方案
为简单起见,每当您通过指针访问成员(数据成员、成员函数)时,都使用箭头。如果你是通过变量或对象的成员(数据成员、成员函数)然后使用点。例如
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 需要访问成员
推荐阅读
- c# - 运行 MS ACCESS 宏的 C# 互操作错误
- android - 无法使用 Firebase 数据填充 RecyclerView 适配器
- javascript - 带有下拉列表的 Node JS 交互式图库
- visual-studio - 使用 nuget 包构建问题
- javascript - 什么将形状和 jQuery 属性添加到我的锚标记?
- php - 使用 array_search() 或 SELECT 子查询的 INSERT 查询会更快吗?
- java - 在按钮单击 RecyclerView 仅显示第一项
- android - 如何在android线性布局中使用50%的宽度和高度
- excel - 过滤列不包含
- ios - 此 iPhone 6 运行 iOS 11.3.1 (15E302),此版本的 Xcode 可能不支持