c++继承构建方法

c++ inheritance Building method

本文关键字:方法 构建 继承 c++      更新时间:2023-10-16

我有一个关于构建方法的问题:

virtual std::string getPerson() const;

我有一个子类Player和一个父类Person。

Class Player:

class Player : public Person {
public:
    Player(const std::string& p_name,const std::string& p_lastname, const int& p_age, const std::string& p_position);
    virtual ~Player();
    virtual Person* clone() const;
    std::string getPosition() const;
    virtual std::string getPerson() const;

private:
    std::string m_position;
};

Class Person:

    class Person {
public:
    Person(const std::string& p_name,const std::string& p_lastname, const int& p_age);
    virtual ~Person();
    virtual std::string getPerson() const;
    std::string getName() const;
    std::string getLastName() const;
    int getAge() const;

private:
    std::string m_name;
    std::string m_lastname;
    int m_age;
};

当我尝试在Player:

中添加此内容时
std::string Player::getPerson()
{
    ostringstream os;
        os << "Name         :" << getName() << "n";
        os << "LastName     :" << getLastName()() << "n";
        os << "Age          :" << getAge()() << "n";
        os << "Position     :" << getPosition();
        return os.str();
}

我得到成员声明未找到

我不能让它工作,我需要打印这样的东西:

Name     : John
Lastname : Smith
Age      : 22
Position : Goalie

您错过了函数签名末尾的const。这应该可以工作:

std::string Player::getPerson() const
{
    ostringstream os;
        os << "Name         :" << getName() << "n";
        os << "LastName     :" << getLastName()() << "n";
        os << "Age          :" << getAge()() << "n";
        os << "Position     :" << getPosition();
        return os.str();
}

但是请记住我在评论中所说的话,并更改函数的名称,或者更好的是,通过重载operator<<使您的类与std::ostream一起工作

简单的事情:

std::string getPerson() const;

不一样
std::string getPerson();

如果你可以使用c++11使用override关键字,那就可以保护你避免这类错误。在您的情况下,编译器会检测到问题。但是如果你有其他的变量,你可以声明一个新的方法而不是重载!