我是 OOP 的新手。最近学习了C++中继承的一些东西,一个protected字段不能从类外访问,但是可以在继承的类中访问。我的代码有一些问题,我不明白出了什么问题:
class Base
{
protected:
int x;
int y;
int z;
public:
Base(int a, int b): x(a), y(b) { cout << "Base constructor" << endl; };
Base(const Base& prev) : x(prev.x), y(prev.y) { cout << "Base copy constructor" << endl; };
void print_x()
{
cout << x << endl;
}
void print_y()
{
cout << y << endl;
}
~Base() { cout << "Base destructor" << endl; };
};
class Derived : public Base
{
public: …Run Code Online (Sandbox Code Playgroud) 考虑以下示例:
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
// Copy constructor
Point(const Point& p2) { x = p2.x; y = p2.y; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(10, 15);
Point p2 = p1;
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = …Run Code Online (Sandbox Code Playgroud)