【问题标题】:Introductory C++: Concatenating strings and returning it in a function?介绍性 C++:连接字符串并在函数中返回它?
【发布时间】:2016-07-30 10:07:01
【问题描述】:

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

【问题讨论】:

  • 你没有做任何事情来输出 display_info() 返回的字符串。返回字符串不会自动打印它。您显然对cout 很熟悉,因为您在调用r2.display_info() 的正上方的行上使用它。
  • using namespace std; 在标头的全局范围内,很容易产生意外的名称冲突。一种解决方法是定义您自己的命名空间。

标签: c++ string concatenation string-concatenation


【解决方案1】:

您的方法 display_info 返回一个包含信息的字符串。它不会打印信息本身。

由于该方法名为“显示信息”,我假设您希望它显示实际信息,因此我建议将其更改为返回 void。并替换“return s;”用“std::cout

【讨论】:

    【解决方案2】:

    你的意思是写:

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 2015-04-08
      • 2014-03-12
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 2015-02-10
      相关资源
      最近更新 更多