【发布时间】:2019-05-01 09:07:46
【问题描述】:
对不起,如果我的标题有点误导,不知道如何总结我目前遇到的问题。
基本上我的任务是使用继承。 但我目前的问题是我不确定如何在同一个函数中返回 int 和字符串以显示在另一个函数中。
下面是例子,希望更有意义。
我尝试过使用引用,但显然我做错了,因为我无法让它工作。
Main.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
值得一提的是,我不能在这个作业中使用结构。
【问题讨论】:
-
如果你想要对象中的所有字段,那与仅仅拥有对象有什么不同呢?看起来你想要的是用这些内容组装一个字符串以便于打印。
标签: c++ oop inheritance