c++ 入门之对象指针

时间:2023-03-09 02:34:23
c++ 入门之对象指针

我们想 像使用基本数据类型一样使用类,自然,类自然也有指针,我们通过下面的代码来领教一下对象指针存在的意义:

 # include "iostream"
# include "string"
# include "ctime"
# include "cstdlib"
const int Arsize = ;
const int MaxLen = ;
int main()
{
using namespace std;
string name;
cout << "Hi,what's your name?\n>>";
cin >> name; cout << name << ",please enter up to " << Arsize
<< "short saying<empty line to quit>:\n";
string sayings[Arsize];//说明这里出现了什么问题
char temp[MaxLen];
int i;
for (i = ; i < Arsize; i++)
{
cout << i + << ":";
cin.get(temp, MaxLen);//cin.get表示的是什么意思
while (cin&& cin.get() != '\n') //注意这里的判别用法
continue;
if (!cin || temp[] == '\n') //说明直接输入“enter”按键则程序会退出
break;
else
sayings[i] = temp;
}
int total = i; if (total > )
{
cout << "Here are your saying:\n";
for (i = ; i < total; i++)
cout << sayings[i] << "\n"; string * shortest = &sayings[];//定义了指针并初始化
string * first = &sayings[];//定义了指针并初始化
for (i = ; i < total; i++)
{
if (sayings[i].length() < shortest->length())
shortest = &sayings[i];
if (sayings[i] < *first)
first = &sayings[i];
}
cout << "shortest saying :\n" << *shortest << endl;
cout << "first alphabetically :\n" << *shortest << endl;
srand(time());
int choice = rand() % total;
string * favorite = new string(sayings[choice]);//使用new定义了指针
cout << "my favorite saying:\n" << *favorite << endl;
delete favorite;
}
else
cout << "Not much to say,eh?\n";
cout << "Bye.\n";
system("pause");
return ;
}

首先注意第16行的代码:使用string类定义了字符串数组,注意我们使用string 定义字符串而不是用c风格的char p[]来定义字符串有诸多的好处:因为string类中既包含了科学的内存管理,同重载了+ ,==,!=,>...这些运算符,来方便我们像使用一般变量一样使用类对象。我们需要形成这样一种意识:即定义的类应该具有重载基本运算符的功能,同时我们即使不知道string能够重载这些,也要站在类的角度,认识到运算符重载对于一般类属性的意义。

cin.get(字符数組名,接收字符数目)用來接收一行字符串,可以接收空格,如下图:

 #include <iostream>
using namespace std;
main ()
{
char a[];
cin.get(a,);
cout<<a<<endl;
} 输入:jkl jkl jkl
输出:jkl jkl jkl 输入:abcdeabcdeabcdeabcdeabcde (输入25个字符)
输出:abcdeabcdeabcdeabcd (接收19个字符+1个'\0')

注意:我们即使是在对象中使用指针,也同样具有&表示取地址,*表示取值,同时通过指针调用方法仍然是->。44行的<很明显是被重载了。

我们需要重点关注的是:

 string * favorite = new string(sayings[choice]);//使用new定义了指针
cout << "my favorite saying:\n" << *favorite << endl;
delete favorite;

要理解这段代码的含义:

new string(sayings[choice]); 是指新开辟了一个内存空间为新的类对象的空间(而这个对象没有取名字),而这个类对象被sayings[choice]初始化,
随后让favorite指向了这块内存空间
需要在意的是delete favorite执行时,也就是说favorite指向的内存空间要被销毁,那么也就意味着临时对象要被销毁。之前说过:对象在销毁时会调用析构函数,
因为执行delete favorite,删除了相应的内存区域,但同时因为对象的销毁,使得析构函数也被调用 我们提出一个题外问题:
我们知道cin是istream类的一个对象,但平常我们在使用普通类对象的时候,我们必须先定义这个对象:class A,但cin似乎并不需要我们定义成istream cin,而可以直接用,
那么我们是否可以采用 诸如istream shuru,这样新生成的对象来替代cin 呢,如果不能又是为什么呢???
当我们试图定义:istream shuru;来替代cin时,程序报错,并提示我们:istream不存在默认构造函数。所以我们无法使用istream来定义新的对象。