#include <iostream> using namespace std; class Vehicle { public: Vehicle(float speed=0,int total=0) { Vehicle::speed = speed; Vehicle::total = total; } protected: float speed;//速度 int total;//最大载人量 }; class Motor { public: Motor(char *motor) { Motor::motortype = motor; } char* SMT(Motor &temp); protected: char *motortype;//发动机型号 }; char* Motor::SMT(Motor &temp) { return temp.motortype; } class Car:public Vehicle//继承的体现 { public: Car(float speed,int total,int aird,char *motortype):Vehicle(speed,total),motor(motortype) { Car::aird = aird; } Motor rm(Car &temp); protected: int aird;//排量 Motor motor;//类组合的体现 }; Motor Car::rm(Car &temp) { return temp.motor; } //-------------------------------------------------------------- void test1(Vehicle &temp) { //中间过程省略 cout<<"qinbin"<<endl; }; void test2(Motor &temp) { cout<<temp.SMT(temp);//读者这里注意一下,temp既是对象也是对象方法的形参 } //-------------------------------------------------------------- int main() { Car a(150,4,250,"奥地利AVL V8"); test1(a); // test2(a);//错误,Car类与Motor类无任何继承关系 //test2(a.rm(a));//如果Car类成员是public的那么可以使用test2(a.motor) test2(a.rm(a)); cin.get(); }
编译不通过,主要是test2 的问题
谢谢了
只需要修改 void test2(Motor &temp)=>void test2(const Motor &temp)
char* Motor::SMT(Motor &temp) => char* Motor::SMT(const Motor &temp) const
在dev c++中可以编译过,在vc 2008 不用修改就能编译过
修改过代码:
#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle(float speed=0,int total=0)
{
Vehicle::speed = speed;
Vehicle::total = total;
}
protected:
float speed;//速度
int total;//最大载人量
};
class Motor
{
public:
Motor(char *motor)
{
Motor::motortype = motor;
}
char* SMT(const Motor &temp) const ;
protected:
char *motortype;//发动机型号
};
char* Motor::SMT(const Motor &temp) const
{
return temp.motortype;
}
class Car:public Vehicle//继承的体现
{
public:
Car(float speed,int total,int aird,char *motortype):Vehicle(speed,total),motor(motortype)
{
Car::aird = aird;
}
Motor rm(Car &temp);
protected:
int aird;//排量
Motor motor;//类组合的体现
};
Motor Car::rm(Car &temp)
{
return temp.motor;
}
//--------------------------------------------------------------
void test1(Vehicle &temp)
{
//中间过程省略
cout<<"qinbin"<<endl;
};
void test2(const Motor &temp)
{
cout << temp.SMT(temp);//读者这里注意一下,temp既是对象也是对象方法的形参
}
//--------------------------------------------------------------
int main()
{
Car a(150,4,250,"奥地利AVL V8");
test1(a);
// test2(a);//错误,Car类与Motor类无任何继承关系
//test2(a.rm(a));//如果Car类成员是public的那么可以使用test2(a.motor)
test2(a.rm(a));
cin.get();
}
Car类与Motor类无任何继承关系
用的类组合,他俩本来就没继承关系
@義丨往昔灬miller: 类组合啊,太高深了,我水平有限,理解不了。
@Launcher: 3Q http://www.cnblogs.com/qbmiller/p/3811761.html 问题解决了
http://www.cnblogs.com/qbmiller/p/3811761.html 已解决