C++里面继承的小问题

来源:百度知道 编辑:UC知道 时间:2024/05/27 01:45:35
#include <iostream.h>

class B {
public:
int x,y;
};

class A : public B {
public:
A(int x,int y) {
x=x;
y=y;
}
void print() {
cout<<"x="<<x<<" y="<<y<<endl;
}
};

void main()
{
A a= A(3,4);
a.print();
}

/*
x=-858993460 y=-858993460
Press any key to continue
*/

请问要怎么样改才能正常显示3和4?

把这一行“A(int x,int y) {”中的“x”和“y”,改成“x1”和“y1”即可。

因为楼主你在一个作用域里面定义的相同的标识符。
#include <iostream.h>

class B {
public:
int x,y;
};

class A : public B {
public:
A(int x1,int y1) { //改为x1,y1。
x=x1; //当然,这里也要改一下。
y=y1; //同上。
}
void print() {
cout<<"x="<<x<<" y="<<y<<endl;
}
};

void main()
{
A a= A(3,4);
a.print();
}

this->x=x;
this->y=y;