簡體   English   中英

C ++入門:連接字符串並在函數中返回它?

[英]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; 
}

您打算寫:

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

另外,將“ using namespace std;”放進去。 頭文件中的文件要求麻煩 不要這樣

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

由於該方法名為“ display info”,因此我假設您希望它顯示實際信息,因此建議您將其更改為返回void。 並替換為“ return s”; “ std :: cout << s;”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM