[英]Introductory C++: Concatenating strings and returning it in a function?
我正在编写一个处理类和对象等的程序。 我必须创建一个Rectangle类并执行该类中的功能,其中之一包括返回一个字符串,其中包含有关Rectangle的所有信息( display_info()
)。 问题是,当我尝试在源代码中使用display_info()
时,屏幕上没有任何显示。 它是空白的。 我在使用此功能时出了什么问题? 我将发布所有代码,以便您可以查看其他地方是否有错误。 谢谢。
标头:
#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返回一个包含信息的字符串。 它不会打印信息本身。
由于该方法名为“ display info”,因此我假设您希望它显示实际信息,因此建议您将其更改为返回void。 并替换为“ return s”; “ std :: cout << s;”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.