gpt4 book ai didi

c++ - 抽象基类或派生类中的类变量?

转载 作者:太空狗 更新时间:2023-10-29 20:34:50 27 4
gpt4 key购买 nike

我有一个抽象类,它有一个字符串变量 owner_。每个派生类都声明了这个变量的名称。将变量放在抽象基类中是更好的做法,还是我可以更好地在派生类中多次实现它?

#include <string>
#include <iostream>

class Pet
{
public:
Pet(const std::string& owner) : owner_(owner) {}
virtual ~Pet() = 0;
virtual void print_status() = 0;
protected:
const std::string owner_;
};

Pet::~Pet() {}

class Dog : public Pet
{
public:
Dog(const std::string& owner) : Pet(owner) {}
~Dog() {};
void print_status()
{
std::string s = "Woof! My owner is ";
s += owner_;
std::cout << s << std::endl;
}
// Or better here?
// private:
// const std::string owner_;
};

class Cat : public Pet
{
public:
Cat(const std::string& owner) : Pet(owner) {}
~Cat() {};
void print_status()
{
std::string s = "Meow! My owner is ";
s += owner_;
std::cout << s << std::endl;
}
// Or better here?
// private:
// const std::string owner_;
};

int main()
{
Dog dog("Mario");
dog.print_status();

Cat cat("Luigi");
cat.print_status();

return 0;
}

最佳答案

IMO 这正是抽象基类的用途:为继承层次结构中的接口(interface)提供通用实现。
我只是更进一步,甚至将接口(interface)与抽象基类分开:

struct IPet {
virtual ~IPet() = {}
virtual void print_status() = 0;
virtual const std::string& get_owner() const = 0;
};

class Pet : public IPet
{
public:
Pet(const std::string& owner) : owner_(owner) {}
virtual const std::string& get_owner() const { return owner_; }
virtual ~Pet() {} // = 0; Don't declare the destructor as pure virtual function
virtual void print_status() = 0;
protected:
std::string owner_;
};

关于c++ - 抽象基类或派生类中的类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46055737/

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