在使用类继承时需要帮助C++
Need help using C++ Class Inheritance
我正在尝试运行以下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::string
与printf()
一起使用。
用
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";
相关文章:
- 需要帮助设置在C++中使用的Potrace
- 在指针的帮助下,文本文件中单词的频率
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 如何在Qbutton的帮助下更改Q对话框的宽度
- 需要帮助将结构数组传递给函数
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 有人可以帮助我处理正则表达式吗?
- C++调用具有 *this 属性的单个帮助程序函数
- C++:需要帮助了解运算符重载错误
- 需要以下代码的帮助,下面的代码有什么问题
- CS1 项目帮助C++
- 用于检查值是否为其任何参数的帮助程序函数
- 需要有关此 if 语句的帮助
- 类型限定宏帮助程序
- CoreCLR 中的检测探查器 - 将帮助程序程序集加载到 dotnet 进程的方法
- NS3 插槽混淆(需要帮助理解)
- 设计帮助 - 为不同类型的消息处理通用接口的设计模式
- 需要帮助查找内存泄漏
- 有人可以帮助我理解这些参数/参数吗?