OOP 和字符串指针的奇怪行为
Weird behavior with OOP and string pointers
这是我的代码:
#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;
}
试试看。不同之处在于,您不初始化类定义中的变量,而是使用构造函数初始化名称。您可以将方法定义拆分为它自己的部分,但它只有一行,并且可以在类定义中
。相关文章:
- strcpy 在类中无法使用字符串指针
- 如何将字符串指针数组转换为字符串类型的智能指针向量?
- 使用conststd::字符串指针作为函数参数
- 将字符串指针传递到C++和Xcode 11.1中不同线程上运行的函数
- OOP 和字符串指针的奇怪行为
- 在 C++ 中通过字符串指针复制字符串变量中的字符串
- 删除字符串指针在struct中的内存
- 字符串指针的排序向量
- C#C /CLR处理REF参数和字符串指针
- 问题在字符串指针中存储单词
- 如何在C++中从字符串指针中获取字符
- 如何使用字符串指针访问映射的键
- 将字符串指针与 NULL 以及 NULL 字符进行比较的目的
- 如何获取字符串指针的值?
- C++ 字符串* 指针未在控制台中正确打印
- Visual Studio C++ 空字符串指针
- 管理C#中返回的字符串指针
- 指向C++中的字符串指针数组的指针
- 如何将结果集设置为字符串指针
- 如何初始化字符串指针