使用另一个Class作为参数在Class内部构造

时间:2014-03-26 03:03:54

标签: c++ class struct

我有一个项目要处理。 它有一个Class Temp,功能很少。 然后是另一个Class Weather,它将数据存储在一个名为Observation的Struct中。这个结构有一个类型为Temp的字段。

Class Temp {
Temp();
Temp(string t);
string getTemp();
void setTemp(string temp); 
};

Class Weather
{ 

@beta

在我的Weather类中 我有几个函数调用类Temp

// Weather.h

public:

void record(Temp temp, float d); // error 'Temp' has not been declared
Temp getTemp() const; // 'Temp' does not name a type

 protected: 
 struct Observation 
 {
   Temp t;
   int deg;
 }; 
 Observation obs[20];
};

 // Weather.cpp 

 void Temp::record(Temp temp, float d){
 obs[i].temp = temp; 
 obs[i].deg = d;
 i++;

 }

我尝试过创建Temp和Weather的实例。 但是我无法进入结构内的温度。

int main(){
Temp t;
Weather w;
w.record(tt,dd); 
}

请指导我......

2 个答案:

答案 0 :(得分:0)

这一行:

obs[i].tp;

没有意义,因为Observation没有名为tp的字段。试试这个:

int record(Temp tp, float d){
 obs[i].t = tp; 
 obs[i].deg = d;
 i++;
}

...

int main(){
Temp t;
Weather w;
int dd=7;
w.record(t,dd); 
}

答案 1 :(得分:0)

为了让你的结构能够访问Temp,你需要公开Temp。 试试这个:

class Temp {
public: 
Temp();
Temp(string t);
string getTemp();
void setTemp(string temp); 
};

现在要获得主要的天气,你需要做同样的事情。

class Weather{
int i;

public:
// method to used to record all values
int record(Temp tp, float d){
obs[i].t = tp;
obs[i].deg = d;
i++;
}

另外,在main中,您将使用以下行将未定义的变量传递给Weather:

w.record(tt,dd);