c++继承构建方法
c++ inheritance Building method
我有一个关于构建方法的问题:
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关键字,那就可以保护你避免这类错误。在您的情况下,编译器会检测到问题。但是如果你有其他的变量,你可以声明一个新的方法而不是重载!
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- 更改命令行 qt5 源代码构建配置的正确/快速方法
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 创建进行生产构建并创建调试信息的C++生成文件的最佳方法?
- 将vector<vector<double>>从x86平台中创建的一个进程发送到x64中构建的另一个进程的最快方法是什么
- 有没有一种方法可以在linux中扫描已构建的ARM库中的函数
- 使用相同方法但不同成员类型构建类的最佳方法
- 使用 openssl 构建静态二进制文件的正确方法是什么?
- 设置用G 构建的二进制版本的任何方法
- cpp 中是否存在一种数据结构,可以轻松地提供一种基于已存在的实例构建新结构的方法
- VS2013在构建容器应用程序时无法识别OCX控制的附加方法
- 是否有任何可能的方法将事件(自定义)附加到在运行时创建的对象?[C 构建器]
- 我们可以在 caa 的构建图方法中只使用初始状态和空状态吗?
- Linux/GCC:是否有一种方法可以检查构建是否与其他机器上的前一个机器相同
- 有什么方法可以为Emscripten构建Zeromq
- ifstream的已删除副本构建器的替代方法
- CMake 构建错误 - 虚拟方法错误缺少 vtable
- 构建数据库,读取方法
- 在Linux上构建具有链接时代码生成功能的静态库的正确方法是什么