c++ - C++ 介绍 : Concatenating strings and returning it in a function?

标签 c++ string concatenation string-concatenation

我正在编写一个处理类和对象等的程序。我必须创建一个 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

矩形.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; 
}

最佳答案

你打算写:

std::cout << r1.display_info();

此外,将“使用命名空间标准;”在头文件中 is asking for trouble .不要这样做。

关于c++ - C++ 介绍 : Concatenating strings and returning it in a function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36511532/

相关文章:

c++ - make for ( rowIdx = 1...) 使用 cuda 线程工作

python - 用括号中的数字Python替换字符串中的数字

c++ - 打印 float ,保持精度

mysql - 使用 CONCAT 和 INNER JOIN MYSQL 选择某些结果

arrays - 草稿选择表生成(又名基于范围列表的多个变量的串联序列)

c++ - vector 引用operator []线程安全写吗?

c++ - 不同目录上的 ifstream

c - 根据字符串的内容返回一定的值

c++ - 添加多个字符串值

c++ - 继承自 OpenCV 类 - 编译错误