在使用类继承时需要帮助C++

Need help using C++ Class Inheritance

本文关键字:帮助 C++ 继承      更新时间:2023-10-16

我正在尝试运行以下C++代码来理解使用MS Visual Studio 15的类继承。生成并运行代码后,我收到一条消息,指出 MS VS 已停止工作。如果有人能帮助我了解我做错了什么,我将不胜感激。

#include<cstdio>
#include<string>
#include<conio.h>
using namespace std;
// BASE CLASS
class Animal {
private:
string _name;
string _type;
string _sound;
Animal() {};     
protected: 
Animal(const string &n, const string &t, const string &s) :_name(n), _type(t), _sound(s) {};    
public: 
void speak() const;     
};
void Animal::speak() const {
printf("%s, the %s says %s.n", _name, _type, _sound);
}
// DERIVED CLASSES 
class Dog :public Animal { 
private:
int walked;
public:
Dog(const string &n) :Animal(n, "dog", "woof"), walked(0) {};
int walk() { return ++walked; }
};

int main(int argc, char ** argv) {    
Dog d("Jimmy"); 
d.speak();          
printf("The dog has been walked %d time(s) today.n", d.walk());        
return 0;
_getch();
}
printf("%s, the %s says %s.n", _name, _type, _sound);

您不能以这种方式将std::stringprintf()一起使用。

printf("%s, the %s says %s.n", _name.c_str(), _type.c_str(), _sound.c_str());

相反。


我宁愿建议使用std::cout让所有内容在 c++ 中无缝运行。

问题是 speak 方法尝试使用 printf 来打印字符串对象。

printf 函数不适合打印 std::string 对象。它确实适用于 char 数组,这些数组用于表示 C 语言中的字符串。 如果你想使用 printf,你需要将你的字符串转换为字符数组。这可以按如下方式完成:

printf("%s, the %s says %s.n", _name.c_str(), _type.c_str(), _sound.c_str());

一个更优雅的解决方案是使用 std::cout 以"C++"方式打印数据:

//include declaration at the top of the document
#include <iostream>
...
//outputs the result
cout <<_name + ", the " + _type + " says " + _sound << "." << endl;

printf%s期望一个 C 样式的 null 结尾字节字符串,而不是std::string,它们不是一回事。所以printf("%s, the %s says %s.n", _name, _type, _sound);不起作用,它不应该编译。

您可以使用std::string::c_str(),这将返回一个const char*。如

printf("%s, the %s says %s.n", _name.c_str(), _type.c_str(), _sound.c_str());

或者将std::cout与以下std::string一起使用:

cout << _name << ", the " << _type << " says " << _sound << ".n";