私はクラスやオブジェクトなどを扱うプログラムを書いています。 Rectangleクラスを作成し、そのクラス内の関数を実行する必要があります。そのうちの1つは、私のRectangle(display_info()
)に関するすべての情報を含む文字列を返します。問題は、ソースにdisplay_info()
を使用しようとすると、何も画面に表示されないということです。それは空白です。私はこの機能に何が間違っているのですか?私はすべてのコードを投稿して、どこか別のエラーがあるかどうかを確認できます。ありがとうございました。初心者のC++:文字列を連結して関数に返すか?
ヘッダー:
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include <iomanip>
#include <string>
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle();
Rectangle(double l, double w);
void set_length(double l);
void set_width(double w);
double get_perimeter();
double get_area();
string display_info();
private:
double length;
double width;
};
#endif
Rectangle.cpp:
#include "Rectangle.h"
Rectangle::Rectangle()
{
length = 0;
width = 0;
}
Rectangle::Rectangle(double l, double w)
{
length = l;
width = w;
}
void Rectangle::set_length(double l)
{
length = l;
return;
}
void Rectangle::set_width(double w)
{
width = w;
return;
}
double Rectangle::get_perimeter()
{
double perimeter = 2 * (length * width);
return perimeter;
}
double Rectangle::get_area()
{
double area = length * width;
return area;
}
string Rectangle::display_info()
{
double perimeter = Rectangle::get_perimeter();
double area = Rectangle::get_area();
string s = "The length is " + to_string(length) + "\nThe width is " + to_string(width) + "\nThe perimeter is " + to_string(perimeter)
+ "\nThe area is " + to_string(area);
return s;
}
出典:
#include "Rectangle.h"
int main()
{
Rectangle r1;
r1.set_length(5);
r1.set_width(4);
cout << "r1's info:" << endl;
r1.display_info();
cout << endl << endl;
Rectangle r2(10, 5);
cout << "r2's info:" << endl;
r2.display_info();
system("pause");
return 0;
}
あなたは* display_info()*によって返された文字列を出力するために何もしませんでした。文字列を返しても自動的には印刷されません。あなたは明らかに 'cout'に精通しています。なぜなら、' r2.display_info() 'の呼び出しのすぐ上の行にそれを使用しているからです。 –
'using namespace std;'ヘッダ内のグローバルスコープで、意図しない名前の衝突を簡単に起こすことがあります。 1つの回避策は、独自の名前空間を定義することです。 –