C++ 是否有其他方法将地址分配给指针变量?

C++ 是否有其他方法将地址分配给指针变量?,c++,C++,在规范文件的第14行中有两个参数(指向char的指针)。 到目前为止,我学到的是指针通过&运算符存储变量的地址,但在int main函数的第#行中,传递了8个直接字符串。 将直接字符串传递给指针变量是否正确 1 // Specification file for the Contact class. 2 #ifndef CONTACTINFO_H 3 #define CONTACTINFO_H 4 #include <cstring> // Needed fo

在规范文件的第14行中有两个参数(指向char的指针)。 到目前为止,我学到的是指针通过&运算符存储变量的地址,但在int main函数的第#行中,传递了8个直接字符串。 将直接字符串传递给指针变量是否正确

1 // Specification file for the Contact class.    
2 #ifndef CONTACTINFO_H    
3 #define CONTACTINFO_H    
4 #include <cstring> // Needed for strlen and strcpy    
5    
6 // ContactInfo class declaration.    
7 class ContactInfo    
8 {    
9 private:    
10 char *name; // The name    
11 char *phone; // The phone number    
12 public:    
13 // Constructor    
14 ContactInfo(char *n, char *p)    
15 { // Allocate just enough memory for the name and phone number.    
16 name = new char[strlen(n) + 1];    
17 phone = new char[strlen(p) + 1];    
18    
19 // Copy the name and phone number to the allocated memory.    
20 strcpy(name, n);    
21 strcpy(phone, p);     
22}    
23 // Destructor    
24 ~ContactInfo()    
25 { delete [] name;    
26 delete [] phone;     
27}    
28 const char *getName() const    
29 { return name; }    
30 const char *getPhoneNumber() const    
31 { return phone; }    
32 };    
33 #endif    


// main     

1 #include <iostream>    
2 #include "ContactInfo.h"    
3 using namespace std;    

4 int main()    
5 {    
6 // Define a ContactInfo object with the following data:    
7 // Name: Kristen Lee Phone Number: 555-2021    
8 ContactInfo entry("Kristen Lee", "555-2021");    
9    
10 // Display the object's data.    
11 cout << "Name: " << entry.getName() << endl;    
12 cout << "Phone Number: " << entry.getPhoneNumber() << endl;    
13 return 0;    
14 }
1//联系人类的规范文件。
2#如果没有联系信息#
3.定义联系人信息
4#包括//strlen和strcpy所需
5.
6//ContactInfo类声明。
7类联系人信息
8 {    
9私人:
10 char*name;//名称
11 char*phone;//电话号码
12公众:
13//Constructor
14联系人信息(字符*n,字符*p)
15{//为姓名和电话号码分配足够的内存。
16 name=新字符[strlen(n)+1];
17电话=新字符[strlen(p)+1];
18
19//将姓名和电话号码复制到分配的内存中。
20个strcpy(名称,n);
21个strcpy(电话,p);
22}    
23//析构函数
24~ContactInfo()
25{删除[]姓名;
26删除[]电话;
27}    
28常量字符*getName()常量
29{返回名称;}
30常量字符*getPhoneNumber()常量
31{回电话;}
32 };    
33#endif
//主要
1#包括
2#包括“ContactInfo.h”
3使用名称空间标准;
4 int main()
5 {    
6//使用以下数据定义ContactInfo对象:
7//姓名:Kristen Lee电话号码:555-2021
8联系人信息输入(“KristenLee”,“555-2021”);
9
10//显示对象的数据。

11 C字符串(也是数组)中的cout是指针类型,必须传递给带有指针参数的函数。&用于获取其他类型的地址并强制转换到指针。

当文本字符串出现在程序中时,它的值实际上是指向字符串的第一个
字符的指针。因此
“Kristen Lee”
已经是一个指针(实际上是一个数组;有关一些技术细节,请参阅)

文字字符串的问题是它们是只读的,因此无论在何处使用它们,都应该使用
const char*
。在构造函数中,无论如何都不打算更改输入字符串,因此无论是否使用文字字符串,声明都应该是
ContactInfo(const char*n,const char*p)



<> > <代码> char *< /> >和代码> const char */c>对字符串的存储不太好,主要是因为在完成时必须要“代码>删除< /代码>。这不容易,不要尝试使用<代码> STD::String < /Cord>存储字符串。

字符串文字是<代码> const <代码>数组>代码> char < /C>。当数组作为参数传递给函数时,传递的值是指向数组第一个元素的指针。为什么不使用
std::string
呢?