OOP 和字符串指针的奇怪行为

Weird behavior with OOP and string pointers

本文关键字:字符串 指针 OOP      更新时间:2023-10-16

这是我的代码:

#include <iostream>
#include <string>
class Human
{
public:
std::string * name = new std::string();
void introduce();
};
void Human::introduce()
{
std::cout << "Hello, my name is " << Human::name << std::endl;
}
int main()
{
Human * martha;
martha->name = new std::string("Martha");
martha->introduce();
return 0;
}

好吧,它应该打印一条消息,例如: "你好,我的名字是玛莎",但它既不打印"你好,我的名字是"字符串,也不打印"玛莎"的名字。为什么会这样?

修复很简单,是完全删除所有指针;请参阅下面的代码。我可以详细解决您的代码中有许多问题,包括内存泄漏、未初始化的变量和指针的一般误用,但似乎您可能来自不同的语言背景,应该花时间从一本好的C++书中学习良好实践以及现代C++中的重要语义和习语。

#include <iostream>
#include <string>
class Human
{
public:
std::string name;
void introduce();
};
void Human::introduce()
{
std::cout << "Hello, my name is " << name << std::endl;
}
int main()
{
Human martha;
martha.name = "Martha";
martha.introduce();
return 0;
}

需要对代码进行少量修改。 下面包含更新的代码以及对所做更改的注释。

#include <iostream>
#include <string>
class Human
{
public:
//Removed pointer to a string
//Cannot have an instantiation inside class declaration
//std::string * name = new std::string();
//Instead have a string member variable
std::string name;
void introduce();
};
void Human::introduce()
{
//Human::name not required this is a member function
//of the same class
std::cout << "Hello, my name is " << name << std::endl; 
}
int main()
{
Human *martha = new Human();
//Assign a constant string to string member variable
martha->name = "Martha";
martha->introduce();
return 0;
}

正如@alter igel所建议的那样 - 权威C++书籍指南和列表将是一个很好的起点。

#include <iostream>
#include <string>
class Human {
public:
void Human(std::string* n) { name = n; }
void introduce();
private:
std::string* name;
};
void Human::introduce() {
std::cout << "Hello, my name is " << name << std::endl;
}
int main() {
Human* martha = new Human(new std:string("Martha"));
martha->introduce();
return 0;
}

试试看。不同之处在于,您不初始化类定义中的变量,而是使用构造函数初始化名称。您可以将方法定义拆分为它自己的部分,但它只有一行,并且可以在类定义中