2016-06-18 7 views
0

MS Visual Studio 15を使用してクラスの継承を理解するために、次のC++コードを実行しようとしています。コードをビルドして実行した後、MS VSが機能しなくなったというメッセージが表示されます。誰かが私が間違っていることを理解するのを助けることができれば、本当に感謝しています。あなたがそのようprintf()std::stringを使用することはできません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("%s, the %s says %s.\n", _name.c_str(), _type.c_str(), _sound.c_str()); 

代わりに。


私はむしろ、すべてがシームレスのC++での作業を取得するためにstd::coutを使用することをお勧めします。

0

printf%sc-style null-terminated byte stringであり、std::stringではなく、同じものではありません。したがってprintf("%s, the %s says %s.\n", _name, _type, _sound);は動作しません。コンパイルしないでください。

std::string::c_str()を使用すると、const char*が返されます。問題が話す方法は、文字列オブジェクトを印刷するためにprintfのを使用しようとすることです

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

ありがとうございます。ヘルプをよろしくお願いいたします。それは今働く。 :) – user3530381

1

:このような

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

などstd::stringstd::coutを使用するように。

printf function is not suitable for printing std::string objects。これは、C言語の文字列を表すために使用されるchar配列で機能します。 とにかくprintfを使いたい場合は、文字列をchar配列に変換する必要があります。これは以下のように行うことができます。

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

よりエレガントな解決策は、STDを使用することにより、「C++」方法でデータを印刷するようになります:: coutの:

誰かが私を助けることができる
//include declaration at the top of the document 
#include <iostream> 
... 
//outputs the result 
cout <<_name + ", the " + _type + " says " + _sound << "." << endl; 
+0

ありがとうございました。私は助けに感謝します。今働いている。 – user3530381

関連する問題