通常这是您将变量从其他类传递给构造函数的方式。
样本A.cpp
#include SampleA.h
#include <iostream>
using namespace std;
SampleA::SampleA(string text)
{
setText(text);
}
string SampleA::getText() {
return text;
}
void SampleA::setText(string text) {
this->text = text;
}
void SampleA::displayText() {
string displayText;
displayText = getText();
cout << displayText << endl;
}
样品A.h
#include <iostream>
#ifndef _testing_ SampleA_h
#define _testing_ SampleA_h
class SampleA {
private:
std::string text;
public :
SampleA()
{
text = "";
};//default constructor
SampleA(std::string);
std::string getText();
void setText(std::string text);
};
主文件
#include <iostream>
#include SampleA.h
using namespace std;
SampleA outputTextValue;
int main () {
string input;
cout << "Enter a text" << endl;
cin >> input;
//pass the value using SampleA class consturctor
SampleA storeText(input);
//output the text from displayText() method from SampleA class
outputTextValue.displayText();
}
我想知道你是否可以对二维数组做同样的事情。
或者更确切地说,如果您想将二维数组值传递给其他类的构造函数,我应该使用什么方法?(*下面显示的代码是错误的,因为它只是一个粗略的例子)
样本A.cpp
#include SampleA.h
#include <iostream>
using namespace std;
SampleA::SampleA(int 2Darray[][2])
{
setText(2Darray[][2]);
}
string SampleA::get2DArray() {
return 2Darray[][2];
}
void SampleA::set2DArray(string int 2Darray[][2]) {
this->2Darray[][2] = 2Darray[][2];
}
void SampleA::displayNumber() {
cout << get2DArray(); << endl;
}
样品A.h
#include <iostream>
#ifndef _testing_ SampleA_h
#define _testing_ SampleA_h
class SampleA {
private:
int 2Darray[][2];
public :
SampleA()
{
2Darray[][2];
};//default constructor
SampleA(2Darray[][2]);
std::string get2DArray();
void set2DArray(2Darray[][2]);
};
主文件
#include <iostream>
#include SampleA.h
using namespace std;
SampleA outputMethod;
int main () {
int storeValue [2][2];
for(int i =0; i<2; i++) {
cout << "Enter first number" << endl;
cin >> storeValue[i][0];
cout << "Enter first number" << endl;
cin >> storeValue[i][1];
}
//pass the 2dArray value using SampleA class consturctor
SampleA storeText(storeValue);
// output method displayNumber() method from SampleA class
outputMethod.displayNumber();
}