在规范文件的第14行中,有两个参数(指向char的指针)。 到目前为止,我了解到的事情是指针存储了&运算符的变量地址,但在第8行的int main函数中传递了直接字符串。 将直接字符串传递给指针变量是否正确?
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 }
答案 0 :(得分:0)
文字字符串出现在您的程序中时,其值实际上是指向该字符串的第一个char
的指针。因此"Kristen Lee"
已经是一个指针(实际上是一个数组;有关一些技术细节,请参见here)。
文字字符串的问题是它们是只读的,因此无论在何处使用const char*
都应使用。在构造函数中,无论如何您都不打算更改输入字符串,因此无论您是否使用文字字符串,声明都应为ContactInfo(const char *n, const char *p)
。
char*
和const char*
都不适合存储字符串,主要是因为完成后必须正确delete
来存储字符串。这不容易!与其尝试这样做,不如考虑使用std::string
来存储字符串。
答案 1 :(得分:-2)
在C字符串中(也是数组)是指针类型,必须通过指针参数传递给函数。 &用于获取其他类型的地址并转换为指针。