gpt4 book ai didi

C++ 使用标准 :string v char* in a base class - base class has a redudant copy of the string

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:36 26 4
gpt4 key购买 nike

在这个 tutorial 的下面的类中它说

you can also make m_speak a std::string, but the downside of doing so is that each Animal will contain a redundant copy of the “speak”

我试图理解这一点,如何使用 string 而不是 char* 只创建 string 的冗余拷贝而不是字符*

#include <string>
#include <iostream>

class Animal
{
protected:
std::string m_name;
const char* m_speak;

// We're making this constructor protected because
// we don't want people creating Animal objects directly,
// but we still want derived classes to be able to use it.
Animal(std::string name, const char* speak)
: m_name(name), m_speak(speak)
{
}

public:
std::string getName() { return m_name; }
const char* speak() { return m_speak; }
};

class Cat: public Animal
{
public:
Cat(std::string name)
: Animal(name, "Meow")
{
}
};

class Dog: public Animal
{
public:
Dog(std::string name)
: Animal(name, "Woof")
{
}
};

最佳答案

与构造函数:

Cat(std::string name) : Animal(name, "Meow")

“Meow”是一个常量,在内存中会有一个地址。编译器将为每个 Cat 使用相同的常量。所有 Cat 对象的 m_speak 变量都将指向那个位置。

如果您将 m_speak 设为 std::string,则变量 m_speak 会将“Meow”复制到其内部缓冲区中。每次创建猫时都会发生这种情况,因此会有很多拷贝。

Dog 和“Woof”也是如此。

关于C++ 使用标准 :string v char* in a base class - base class has a redudant copy of the string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49652536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com