抱歉,如果我的标题有点误导,我不确定如何总结我目前遇到的问题。
基本上我的任务是使用继承。 但我现在的问题是我不确定如何在同一个函数中返回 int 和字符串以在另一个函数中显示。
下面是示例,希望它更有意义。
我试过使用引用,但显然我做错了,因为我无法让它工作。
主要.cpp:
#include <iostream>
#include "Text.h"
int main(){
Text text1;
text1.SetText("Arial", 12, "Black", "This is a sample text"); //String, int, string, string
text1.PrintText();
return 0;
}
文本.h:
#ifndef TEXT_H
#define TEXT_H
class Text{
public:
Text();
void SetText(std::string font, int size, std::string color, std::string data);
void GetParameters(); /*This is the problem area. I have setText that will set it, but how do I return these values to use in PrintText if it has different variable types?*/
void PrintText();
private:
std::string font;
int size;
std::string color;
std::string data;
};
#endif // TEXT_H
文本.cpp:
#include <iostream>
#include "Text.h"
Text::Text(){
}
void Text::SetText(std::string font, int size, std::string color, std::string data){
font = font;
size = size;
color = color;
data = data;
}
void Text::GetParameters (){//Any pointers in this would be much appreciated.
}
void Text::PrintText(){
cout <<"Text parameters are: " <<GetParameters() <<endl;//this is where Im trying to simply display the font, size, color and data values.
}
如果它有点冗长,我很抱歉,我不确定要包括多少才能正确说明我遇到的问题。
我试图达到的结果是非常基本的:
Text parameters are:
Font = Arial
Size = 12
Color = Black
Data = This is a sample text
值得一提的是,我不能在此作业中使用结构。
最佳答案
看起来您只需要返回一个字符串作为函数 GetParameters
的输出。请注意,当前您的返回类型是 void
(不返回任何内容)。
示例代码:
std::string Text::GetParameters() {
std::string stringToReturn = "";
stringToReturn += "Font = " + font + "\n";
stringToReturn += "Size = " + std::to_string(size) + "\n";
// leave it to you to figure out the rest of the function
return stringToReturn;
}
关于c++ - 返回不同类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55933926/