#include <iostream> using namespace std; class BaseClass { int m_x; public: int GetX() {return m_x;} void SetX(int x) {m_x=x;} }; class DerivedClass: (1) { int m_y; public: void DisplayXY() {cout<< (2) <<','<<m_y<<endl;} void SetY(int y) {m_y=y;} }; int main() { DerivedClass d; (3) d.SetY(10); d.DisplayXY(); return 0; }
时间: 2024-03-24 18:39:11 浏览: 67
上面的代码中,应该在(1)处使用冒号语法继承BaseClass,如下所示:
```c++
class DerivedClass : public BaseClass {
int m_y;
public:
void DisplayXY() {
cout << GetX() << ',' << m_y << endl;
}
void SetY(int y) {
m_y = y;
}
};
```
在(3)处创建DerivedClass的对象d,并调用SetY函数设置成员变量m_y的值为10。接着调用d的DisplayXY函数,在控制台上输出m_x和m_y的值,中间用逗号隔开。由于DerivedClass继承了BaseClass的GetX函数,因此可以在DerivedClass中直接调用该函数获取m_x的值。
相关问题
#include <iostream> using namespace std; //在此处补充你的代码 class Derived : public Base { public: int Bar(char x) { return (int)(-x); } int Bar(int x) { return (x / 2);
缺少代码结尾的大括号和分号。完整代码应该是这样的:
```
#include <iostream>
using namespace std;
class Base {
public:
Base() {}
virtual ~Base() {}
};
class Derived : public Base {
public:
int Bar(char x) {
return (int)(-x);
}
int Bar(int x) {
return (x / 2);
}
};
```
#include <iostream> using namespace std; class Point{ public: Point(int x1); int getx() { return x; } protected: int x; }; Point::Point(int x1) { x=x1; cout<<"执行基类的构造函数"<<endl; } class Circle:public Point{ public: Circle(int x1,int y1); int gety() { return y; } protected: int y; }; Circle::Circle(int x1,int y1):Point(x1) { y=y1; cout<<"执行派生类的构造函数"<<endl; } int main() { Circle c(2,1); cout<<"x="<<c.getx<<endl; cout<<"y="<<c.gety<<endl; return 0; }
在 `main` 函数中调用 `getx` 函数时,应该加上括号,即 `c.getx()`,而不是 `c.getx`。请修改以下代码:
```c++
#include <iostream>
using namespace std;
class Point{
public:
Point(int x1);
int getx()
{
return x;
}
protected:
int x;
};
Point::Point(int x1) {
x=x1;
cout<<"执行基类的构造函数"<<endl;
}
class Circle:public Point{
public:
Circle(int x1,int y1);
int gety()
{
return y;
}
protected:
int y;
};
Circle::Circle(int x1,int y1):Point(x1) {
y=y1;
cout<<"执行派生类的构造函数"<<endl;
}
int main() {
Circle c(2,1);
cout<<"x="<<c.getx()<<endl; //注意这里调用 getx 函数时要加上括号
cout<<"y="<<c.gety()<<endl;
return 0;
}
```
阅读全文