【发布时间】:2017-07-20 10:42:11
【问题描述】:
我正在继续使用 C++ 学习 uni,但我遇到了一些关于指针、常量参数和类实现的所有基础知识的严重理解问题(与 C++ 相比,Java 中的这些实现非常简单)
我通常使用 Java,所以 C++ 对我来说非常陌生。
这是我的“Person”类的简单标题:
#ifndef Person_h
#define Person_h
class Person
{
private:
char* name;
char* adress;
char* phone;
public:
Person();
Person(char const *name, char const *adress, char const *phone);
Person(const Person &other);
~Person();
void setName(char const *name);
char* getName() const;
void setAdress(char const *adress);
char* getAdress() const;
void setPhone(char const *phone);
char* getPhone() const;
};
#endif // !Person_h
问题从这里开始。为什么我应该使用 char 指针而不是实际的 char 变量?我猜这是为了节省内存或提高性能的一些约定?
这是我们教授编码的方式,并试图让我们理解指针和const等的使用。
现在这是我的类的实现:
#include "Person.h"
//Person.h class implementation
Person::Person()
{
Person::name = new (char[64]);
Person::adress = new (char[64]);
Person::phone = new (char[64]);
}
Person::Person(const char *name, const char *adress , const char *phone)
{
Person::name = new (char[64]);
Person::adress = new (char[64]);
Person::phone = new (char[64]);
setName(name);
setAdress(adress);
setPhone(phone);
};
Person::Person(Person const &other)
{
Person::name = new (char[64]);
Person::adress = new (char[64]);
Person::phone = new (char[64]);
setName(other.getName);
setAdress(other.getAdress);
setPhone(other.getPhone);
};
Person::~Person()
{
delete [] name;
delete [] adress;
delete [] phone;
};
void Person::setName(const char *name)
{
this->name = name;
};
char* Person::getName() const
{
return name;
};
void Person::setAdress(char const *adress)
{
this->adress = adress;
};
char* Person::getAdress() const
{
return adress;
};
void Person::setPhone(char const *phone)
{
this->phone = phone;
};
char* Person::getPhone() const
{
return phone;
};
我们应该学会手动为元素分配内存并尝试照顾整体内存管理。因此,对 setter 函数使用 const 参数。我想这是为了不改变元素参数?我很困惑,基本上……
而我的 IDE (MS VisualStudio 2015) 将以下行强调为错误:
void Person::setName(const char *name)
{
this->name = name; //error
};
“'const char *'类型的值不能分配给'char *'类型的实体”
那么当我无法分配这些值时,为什么要使用const?或者我怎样才能“un-const”那些,而不使成员变量本身const?
这整件事现在对我来说只是一个很大的困惑。
编辑:我必须在考试中使用 C 字符串,这是为了了解指针和内存管理,参考我们的教授。
【问题讨论】:
-
> 为什么我应该使用 char 指针而不是实际的 char 变量? std::string。
-
您应该使用
std::string来保存字符串数据,而不是裸指针。在我看来,您需要一本好的 C++ 书籍。 -
在分配C风格的字符串时,不要使用
=,而是使用strcpy来复制字符串值。 -
在 C 和 C++ 中,指针可用于传递单个变量或变量数组。然而,指针本身不包含关于它是否包含单个项目的地址或数组内第一项的地址的信息。所以你需要从上下文中弄清楚。在您的情况下,
name被假定为指向以空字符结尾的字符数组(即 C 样式字符串)的指针。 -
@BoPersson 谢谢,现在我明白了......所以这都是与 C 相关的。想知道 C++ 中没有字符串,但我们使用 C 方面(如 C 样式字符串)来更好地理解“幕后”操作。
标签: c++ class pointers constants getter-setter