2016-06-18 82 views
0

我想运行下面的C++代码来理解使用MS Visual Studio 15的类继承。生成并运行代码后,我收到消息说MS VS已停止工作。如果有人能帮助我理解我做错了什么,我会非常感激。需要帮助使用C++类继承

#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(); 
} 
+0

'有人能帮助我了解我做错了什么'你有VS2015 –

+0

服从警告[编译时](http://coliru.stacked-crooked.com/a/b01383841d47037d)钻石问题! –

回答

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

你不能printf()这种方式使用std::string

使用

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

代替。


我宁可推荐使用std::cout让一切都能在C++中无缝工作。

0

printf%s预计c-style null-terminated byte string,而不是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::coutstd::string,如:

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

谢谢。感谢帮助。它现在有效。 :) – user3530381

1

的问题是讲方法试图以打印一个字符串对象用printf。

The printf function is not suitable for printing std::string objects。它对char数组起作用,用于表示C语言中的字符串。 如果您想要使用printf,您需要将字符串转换为char数组。

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

更好的解决方案,将是印在“C++”的方式中的数据,通过使用std ::法院:这可以如下进行

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

谢谢。我很感激帮助。它的工作现在。 – user3530381